我的问题与此非常相似question这里。我有一个 AuthenticationService
类,它生成一个 HttpClient
PostAsync()
并且当我从 ASP 项目运行它时从不返回结果,但是当我在一个控制台应用程序中实现它,它工作得很好。
这是我的身份验证服务类:
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);
这是我的 Controller 调用服务:
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();
}
这是我如何使用控制台应用程序测试服务的示例,它运行得很好。
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 应用程序有(参见 Stephen Cleary's Don't Block on Async Code )。您应该在 Controller 中使用 Signin
方法 async
和 await
调用 _authenticationService.Authenticate
来解决死锁问题。
关于c# - HttpClient PostAsync() 从不返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078296/