c# - HttpClient PostAsync() 从不返回响应

标签 c# asp.net asynchronous httpclient

我的问题与此非常相似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 方法 asyncawait 调用 _authenticationService.Authenticate 来解决死锁问题。

关于c# - HttpClient PostAsync() 从不返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078296/

相关文章:

c# - 执行读取器 : Connection property has not been initialized error issue

Javascript 和女孩的回调——两者的问题

c# - 并行执行任务 - Silverlight

c# - 在 .NET、C# 中绘制形状的形状线问题

c# - 在 SQL SERVER Reporting Services (SSRS) 中显示 rtf 数据

javascript - 在 FullCalendar 中更改日期背景颜色

javascript - Node.js:识别脚本是异步的还是非阻塞的

c# - WPF MVVM 绑定(bind)相关源

c# - 获取请求的 URL 或操作参数 i MediaTypeFormatter.ReadFromStreamAsync

c# - 手动将 SelectListItem 添加到 SelectList 以在 DropDownListFor 中使用