【发布时间】:2020-03-21 15:05:15
【问题描述】:
我在设置简单的 WebApi 时遇到问题。我相信问题出在我的 webApi 代码上。当我在 Chrome 中点击此端点时,我可以看到消息“WebApi is up and running”。使用驻留在控制台应用程序中的 HttpClient,我没有得到响应。然后我尝试了邮递员,但我也没有得到回应。我的 WebApi 出了什么问题?
在 HttpClient 中,我添加了两个 Nuget 包:Microsoft.AspNet.WebApi.Client 和 Newtonsoft.Json
httpClient 和 WebApi 都是用 .Core 3.1 编写的
WebAPI 中的代码:
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");
【问题讨论】:
-
您需要通过
var data = await get.Content.ReadAsStringAsync();获取从Web API 返回的实际内容 -
HttpResponseMessage get = await client.GetAsync("api/test");不返回任何东西并且有一个异常等待。它永远不会到达您建议的另一条线路。
-
那么可能想要使用 try..catch 并捕获异常并在此处分享异常消息...如果发生异常,那么我们需要知道它。
标签: c# asp.net-web-api dotnet-httpclient