2

I have next part of code :

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

This makes call to my Web Api. I have checked if it's really works with fiddler - as result I can see response what i espect (Bearer token). But in code this response are never received.

What is the problem?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
demo
  • 6,038
  • 19
  • 75
  • 149

1 Answers1

3

This:

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

Causes a classic deadlock. You shouldn't be blocking on async code with Task.Result or Task.Wait. Instead, you need to go "async all the way" and await on it too, making the method higher up the call stack async Task as well:

public async Task GetApiTokenAsync()
{
    var token = await GetAPIToken(UserName, Password, ApiBaseUri);
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321