在PostAsync之后没有收到响应

时间:2015-11-10 16:17:49

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

我有下一部分代码:

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。我已经检查过它是否真的适用于小提琴手 - 结果我可以看到我所期待的响应(持票人令牌)。但在代码中,这种反应从未收到过。

有什么问题?

1 个答案:

答案 0 :(得分:2)

此:

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

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

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