【问题标题】:Didn't get response from GetAsync API of HttpClient in MVC applications在 MVC 应用程序中没有从 HttpClient 的 GetAsync API 得到响应
【发布时间】:2021-05-26 10:19:07
【问题描述】:

我面临一个问题,即在 MVC 应用程序(目标框架 - .Net Framework 4.7)中没有从 HttpClient 的 GetAsync API 获得响应,而在具有相同 sn-p 的 Web 服务和控制台应用程序中获得响应。这里我附上了我正在尝试执行的代码 sn-p。

public void Get()
{
    var response = Gettasks().Result;
}
public static async Task<HttpResponseMessage> GetTasks()
{
     var response = new HttpResponseMessage();
     try
     {
          using (var client = new HttpClient())
          {
               response = await client.GetAsync("https://www.google.com");
          }
     }
     catch (Exception exception)
     {
          Console.WriteLine(exception.Message);
     }
     return response;
}

我卡在 response = await client.GetAsync("https://www.google.com"); 这一行,执行此语句后没有得到任何响应。

如果有人可以为此建议解决方案或提供适合您的修复/解决方案。

【问题讨论】:

  • 错误信息是什么?
  • 听起来像是死机,你可以试试:response = await client.GetAsync("https://www.google.com").ConfigureAwait(false);.
  • @AliK API调用没有错误返回。
  • 尝试使用 Net 4.7.2 或更高版本。 4.7.2 中有针对 TLS 问题的修复。
  • 如果你没有错误,你怎么知道它不工作?检查响应是否为空,在这种情况下它不起作用。检查返回的响应状态码,如果它是 200 则它正在工作。

标签: c# entity-framework httpclient


【解决方案1】:

您看到的是deadlock because the code is blocking on an asynchronous method

最好的解决办法是移除阻塞:

public async Task Get()
{
  var response = await Gettasks();
}

之所以会发生这种死锁,是因为await captures a context,而 ASP.NET(pre-Core)的上下文一次只允许一个线程,并且代码在该上下文中阻塞了一个线程 (.Result),从而阻止了@ 987654326@从完成。

上下文和阻塞都是看到这种死锁所必需的。在其他情况下,没有上下文,因此不会发生死锁。由于 ASP.NET (pre-Core) 有上下文,这里的正确解决方案是移除阻塞。

【讨论】:

    【解决方案2】:

    不确定您是否尝试过以下对我有用的方法。

    using (HttpClient client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(Environment.GetEnvironmentVariable("BaseAddress"));
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                         var requestUri = Environment.GetEnvironmentVariable("Uri");
                        HttpResponseMessage response = await client.GetAsync(requestUri);
                        if (response.IsSuccessStatusCode)
                        {
                            var data = await response.Content.ReadAsStringAsync();
                        }        
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多