Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
This line of code:
C#
await response.Content.ReadAsAsync<AuthenticatedUser>(); 
returns "null", when it's supposed to return an <AuthenticatedUser> with a Username and Password.
I saw a similar problem here:Response.content.readasasync returns null[^], however, the answer provided did not help me.

What I have tried:

Here's what I've got so far:
C#
public async Task<AuthenticatedUser> Authenticate(string username, string password)
        {
            var data = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", username),
                new KeyValuePair<string, string>("passsword", password)
            });
            using (HttpResponseMessage response = await apiClient.PostAsync("/token", data))
            {
                if (response.IsSuccessStatusCode)
                {
                    var result= await response.Content.ReadAsAsync<AuthenticatedUser>();
                    return result;
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }

I tried replacing
C#
await response.Content.ReadAsAsync<AuthenticatedUser>();

with
C#
await response.Content.ReadAsAsync<object>();
, which in return required changing the void and interface to
Task<object>
, too. To no avail.
I also tried replacing var with AuthenticatedUser and it didn't work either. Any ideas how to bypass this problem?
Posted
Updated 18-Jan-20 19:55pm
v2
Comments
Member 14575056 28-Dec-19 11:13am    
I don't know if it's of importance, but I use this method in another class - LoginViewModel, where I apply Username and Password parameters to the Authenticate() void. I made sure the values from the textboxes are parsed correctly.
Richard MacCutchan 28-Dec-19 12:21pm    
Use the debugger to see exactly what is being returned in the response.
Member 14575056 28-Dec-19 12:35pm    
Thanks.I just discovered that var "data" in Authenticate() is also null and I think that's why "response" is null, too. The "username" and "password" however have been sent to var "data" correctly. What could be the problem?
Richard MacCutchan 28-Dec-19 12:56pm    
OK, so that should tell you that something is wrong in the authentication process at the server. The data you are sending is incorrect, or in an incorrect format, etc. But that is not something we can help with.
Member 14575056 28-Dec-19 12:58pm    
OK, thanks for helping.

1 solution

You can use Json.net for deserializing your response, Using streams would give you better performance, Check this function below

C#
private static async Task<List<Model>> DeserializeOptimizedFromStreamCallAsync(CancellationToken cancellationToken)
{
    using (var client = new HttpClient())
    using (var request = new HttpRequestMessage(HttpMethod.Get, Url))
    using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
    {
        var stream = await response.Content.ReadAsStreamAsync();

        if (response.IsSuccessStatusCode)
            return DeserializeJsonFromStream<List<Model>>(stream);

        var content = await StreamToStringAsync(stream);
        throw new ApiException
        {
          StatusCode = (int)response.StatusCode,
          Content = content
        };
    }
}


If you're interested please check this link Efficient api calls with HttpClient and JSON.NET | John Thiriet[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900