[英]HttpClient GetAsync response content is different from what Fiddler is giving me
[英]Didn't get response from GetAsync API of HttpClient in MVC applications
我面临一个问题,即在 MVC 应用程序(目标框架-.Net Framework 4.7)中没有从 HttpClient 的 GetAsync API 获得响应,而在 web 服务和控制台应用程序中获得响应具有相同的片段。 在这里,我附上了我正在尝试执行的代码片段。
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"); 这一行,执行此语句后没有得到任何响应。
如果有人可以请为此建议解决方案或提供适合您的修复/解决方案。
您会看到死锁,因为代码在异步方法上阻塞。
最好的解决方法是删除阻塞:
public async Task Get()
{
var response = await Gettasks();
}
之所以会发生这种死锁,是因为await
捕获了一个 context ,而 ASP.NET (pre-Core)有一个一次只允许一个线程的上下文,并且代码在该上下文中阻塞了一个线程( .Result
),这会阻止GetTasks
完成。
要看到这种死锁,上下文和阻塞都是必要的。 在其他情况下,没有上下文,因此不会发生死锁。 由于 ASP.NET (pre-Core) 有上下文,这里正确的解决方案是移除阻塞。
不确定您是否尝试过以下对我有用的方法。
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.