HttpClient PostAsync()永不返回响应 [英] HttpClient PostAsync() never return response
问题描述
我的问题与此处的问题非常相似.我有一个AuthenticationService
类,它生成一个HttpClient
PostAsync()
,并且从ASP项目中运行它时从不返回结果,但是当我在Console应用程序中实现它时,它就可以正常工作.
My problem is very similar to this question here. I have an AuthenticationService
class that makes an HttpClient
PostAsync()
and never returns the result when I am running it from the ASP project, but when I implement it in a Console app it works just fine.
这是我的身份验证服务类:
This is my Authentication Service class:
public class AuthenticationService : BaseService
{
public async Task<Token> Authenticate (User user, string url)
{
string json = JsonConvert.SerializeObject(user);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync(url, content);
string responseContent = await response.Content.ReadAsStringAsync();
Token token = JsonConvert.DeserializeObject<Token>(responseContent);
return token;
}
}
它在这里挂着:HttpResponseMessage response = await _client.PostAsync(url, content);
这是我的控制器在调用该服务:
Here is my Controller calling the service:
public ActionResult Signin(User user)
{
// no token needed to be send - we are requesting one
Token token = _authenticationService.Authenticate(user, ApiUrls.Signin).Result;
return View();
}
这是我如何使用控制台应用程序测试服务的示例,它运行得很好.
Here is an example of how I have been testing the service using a Console app, and it runs just fine.
class Program
{
static void Main()
{
AuthenticationService auth = new AuthenticationService();
User u = new User()
{
email = "email@hotmail.com",
password = "password123"
};
Token newToken = auth.Authenticate(u, ApiUrls.Signin).Result;
Console.Write("Content: " + newToken.user._id);
Console.Read();
}
}
推荐答案
由于您使用的是.Result
,因此最终将导致代码中的死锁.之所以在控制台应用程序中运行,是因为控制台应用程序没有上下文,但是ASP.NET应用程序有上下文(请参见).您应该在控制器async
中创建Signin
方法,并调用await
来解决死锁问题.
Since you are using .Result
, this will end up causing a deadlock in your code. The reason this is working in a console application is because console applications don't have contexts, but ASP.NET apps do (see Stephen Cleary's Don't Block on Async Code). You should make the Signin
method in your controller async
and await
the call to _authenticationService.Authenticate
to resolve the deadlock issue.
这篇关于HttpClient PostAsync()永不返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!