PostAsync 后未收到响应

Not receiving response after PostAsync

我有下一部分代码:

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();
}

这会调用我的网站 Api。我已经检查过它是否真的适用于 fiddler - 结果我可以看到我所期望的响应(不记名令牌)。但在代码中,从未收到此响应。

有什么问题?

这个:

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

导致经典死锁。 You shouldn't be blocking on async codeTask.ResultTask.Wait。相反,您需要去 "async all the way" 并等待它,使该方法在调用堆栈中更高 async Task as well:

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