[英]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.我面临一个问题,即在 MVC 应用程序(目标框架-.Net Framework 4.7)中没有从 HttpClient 的 GetAsync API 获得响应,而在 web 服务和控制台应用程序中获得响应具有相同的片段。 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");我卡在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.之所以会发生这种死锁,是因为
await
捕获了一个 context ,而 ASP.NET (pre-Core)有一个一次只允许一个线程的上下文,并且代码在该上下文中阻塞了一个线程( .Result
),这会阻止GetTasks
完成。
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.
由于 ASP.NET (pre-Core) 有上下文,这里正确的解决方案是移除阻塞。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.