Reputation: 211
I'm making a basic POST to receive an auth Token from an API. My code starts the Task from a button press.
Task<DataClass.AuthenticationToken> token = GetAuthTokenAsync(tbUsername.Text.Trim(), tbPassword.Text.Trim());
The task should return my token information in a data structure defined in "dataclass"
private async Task<DataClass.AuthenticationToken> GetAuthTokenAsync(string username, string password)
{
string requestURL = DataClass.CloudAPIBaseURL + DataClass.CloudTokenURL;
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
DataClass.AuthenticationRequest request = new DataClass.AuthenticationRequest
{
username = username,
password = password
};
DataClass.AuthenticationToken token = new DataClass.AuthenticationToken();
// Post request
response = await client.PostAsJsonAsync(requestURL, request);
//never gets here!!!
// I will complete coding once I get the response.
//string statusCode = response.StatusCode.ToString();
return token;
}
Using Fiddler, I see my POST going out and the response containing the correct authorizing data. For some reason, the async await is not returning.
Upvotes: 0
Views: 585
Reputation: 211
Trying the last suggestion:
DataClass.AuthenticationToken token = await GetAuthTokenAsync(tbUsername.Text.Trim(), tbPassword.Text.Trim());
the compiler does not allow this as a call to an async Task. The format I used to invoke the Task is correct. Continued experimenting for 5 days, I landed on NOT using the TASK await method. Instead I changed the Task to a function GetAuthToken(parameters). Using the PostAsJsonAsync without await and adding .Result, the method awaits for a result.
HttpResponseMessage response = client.PostAsJsonAsync(requestURL, request).Result;
if (response.IsSuccessStatusCode)
{
// Ok
string data = response.Content.ReadAsStringAsync().Result;
thisToken = Newtonsoft.Json.JsonConvert.DeserializeObject<DataClass.AuthenticationToken>(data);
}
I used Newtonsoft to deserialize the data and voila. I can continue with my project!
Note to all those who tried to help. Thank you. It would be helpful however, if you first test your suggestions as some were just not valid coding syntax.
Upvotes: 0
Reputation: 1664
The issue could be that the call to GetAuthTokenAsync
isn't being awaited:
Task<DataClass.AuthenticationToken> token = GetAuthTokenAsync(tbUsername.Text.Trim(), tbPassword.Text.Trim());
Try this:
DataClass.AuthenticationToken token = await GetAuthTokenAsync(tbUsername.Text.Trim(), tbPassword.Text.Trim());
Upvotes: 1
Reputation: 337
You can try first to check whether client.PostAsJsonAsync(requestURL, request)
will return a value called synchronously i.e without awaiting the call:
response = client.PostAsJsonAsync(requestURL, request).Result;
If it returns a value maybe the problem is in the surrounding code that calls GetAuthTokenAsync
i.e. it does not wait for the Task to complete or similar issue.
Upvotes: 0