简体   繁体   中英

Didn't get response from GetAsync API of HttpClient in MVC applications

I am facing an issue regarding not getting response from GetAsync API of HttpClient in MVC Applications(Target Framework -.Net Framework 4.7) whereas getting response in web services and console applications with same snippet. Here I have attached code snippet which I am trying to execute.

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;
}

I am getting stuck on response = await client.GetAsync("https://www.google.com"); this line and not getting any response after executing this statement.

If anyone can please suggest solution for this or provide fix/solution which works for you.

You're seeing a deadlock because the code is blocking on an asynchronous method .

The best fix is to remove the blocking:

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

This deadlock happens because await captures a context , and ASP.NET (pre-Core) has a context that only allows one thread at a time, and the code blocks a thread ( .Result ) in that context, which prevents GetTasks from completing.

Both the context and the blocking are necessary to see this kind of deadlock. In the other scenarios, there is no context, so that is why the deadlock does not occur. Since ASP.NET (pre-Core) has a context, the proper solution here is to remove the blocking.

Not sure whether you have tried following which is working for me.

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();
                    }        
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM