【问题标题】:WebApi GET is not hit in Postman but works in chromeWebApi GET 在 Postman 中未命中,但在 chrome 中有效
【发布时间】: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


【解决方案1】:

正如评论部分中提到的@Chetan Ranpariya,您需要使用Content.ReadAsStringAsync();来异步获取结果:

HttpResponseMessage get = await client.GetAsync("api/test");
var content = await get.Content.ReadAsStringAsync();

【讨论】:

    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 2017-08-04
    • 2016-07-11
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2021-09-19
    相关资源
    最近更新 更多