【问题标题】:Not receiving response after PostAsync [duplicate]PostAsync 后未收到响应 [重复]
【发布时间】:2016-02-11 14:28:13
【问题描述】:

我有下一部分代码:

using (var client = new HttpClient()) // from Windows.Web.Http;
{
    //setup client
    var tokenUri = new Uri(apiBaseUri + "/token");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
                        new HttpMediaTypeWithQualityHeaderValue("application/json"));

    //setup login data
    IHttpContent formContent = new HttpFormUrlEncodedContent(new[]
    {
         new KeyValuePair<string, string>("grant_type", "password"),
         new KeyValuePair<string, string>("username", userName),
         new KeyValuePair<string, string>("password", password),
    });

    //send request
    HttpResponseMessage responseMessage = await client.PostAsync(tokenUri, formContent);

    //get access token from response body
    var responseJson = await responseMessage.Content.ReadAsStringAsync();
    var jObject = JObject.Parse(responseJson);
    return jObject.GetValue("access_token").ToString();
}

这会调用我的 Web Api。我检查了它是否真的适用于提琴手 - 结果我可以看到我所期望的响应(不记名令牌)。但是在代码中,这个响应永远不会被接收到。

有什么问题?

【问题讨论】:

  • 什么意思,responseMessage 为空?
  • @AndyWiesendanger,什么都没有......也许我应该设置一些超时来确定,但我等了很多时间,什么也没发生
  • 你是怎么调用这个方法的?你是用Task.Result 屏蔽它吗?
  • 我说的是调用这个方法的方法
  • @YuvalItzchakov 比是 var token = GetAPIToken(UserName, Password, ApiBaseUri).Result; 类似的东西

标签: c# post asynchronous async-await asp.net-web-api2


【解决方案1】:

这个:

var token = GetAPIToken(UserName, Password, ApiBaseUri).Result;

导致典型的死锁。 You shouldn't be blocking on async codeTask.ResultTask.Wait。相反,您需要“一直异步”并等待它,使该方法在调用堆栈中更高async Task as well

public async Task GetApiTokenAsync()
{
    var token = await GetAPIToken(UserName, Password, ApiBaseUri);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多