C# WebApi GET在《邮递员》中不受欢迎,但在chrome中起作用
我在设置一个简单的WebApi时遇到了问题。我相信问题在于我的webApi代码。当我在Chrome中点击这个端点时,我能够看到消息“WebApi已启动并正在运行”。对于驻留在控制台应用程序中的HttpClient,我没有得到响应。然后我尝试了邮递员,但也没有得到回应。我的WebApi有什么问题 在HttpClient中,我添加了两个Nuget包:Microsoft.AspNet.WebApi.Client和Newtonsoft.Json httpClient和WebApi都是用.Core 3.1编写的 WebAPI中的代码:C# WebApi GET在《邮递员》中不受欢迎,但在chrome中起作用,c#,asp.net-web-api,dotnet-httpclient,C#,Asp.net Web Api,Dotnet Httpclient,我在设置一个简单的WebApi时遇到了问题。我相信问题在于我的webApi代码。当我在Chrome中点击这个端点时,我能够看到消息“WebApi已启动并正在运行”。对于驻留在控制台应用程序中的HttpClient,我没有得到响应。然后我尝试了邮递员,但也没有得到回应。我的WebApi有什么问题 在HttpClient中,我添加了两个Nuget包:Microsoft.AspNet.WebApi.Client和Newtonsoft.Json httpClient和WebApi都是用.Core 3.1
public class TestController : Controller
{
public TestController ()
{
}
[HttpGet("api/test")]
public string Get()
{
return "WebApi is up and running.";
}
}
HttpClient中的代码
HttpClient client = new HttpClient(new HttpClientHandler()
{
UseDefaultCredentials = true
});
// Update port # in the following line.
client.BaseAddress = new Uri("http://localhost:44335/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage get = await client.GetAsync("api/test");
正如注释部分中提到的@Chetan Ranpariya,您需要使用异步获取结果:
HttpResponseMessage get = await client.GetAsync("api/test");
var content = await get.Content.ReadAsStringAsync();
您需要执行
var data=wait get.Content.ReadAsStringAsync()
获取从web APIHttpResponseMessage get=wait client.GetAsync(“api/test”)返回的实际内容;不返回任何内容,并且正在等待异常。它永远不会到达您建议的另一行。然后to可能希望使用try..catch和catch异常并在此处共享异常消息。。。如果发生异常,那么我们需要知道它。