Gabms Gabms - 1 year ago 100
C# Question

Managing returncode from Newtonsoft.Json when not authorized

We have using an implementation login on a JWT portal.
When I post a valid user/pass, we have a token ok. But whe I post a invalid user/pass, the response has this format:

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Cache-Control: no-cache
Set-Cookie: dnn_IsMobile=False; path=/; HttpOnly
Set-Cookie: .ASPXANONYMOUS=YrYcKYrviiUjmN7dSAd2DYWBO5W_Nj2yS_79eZ473OtallQXmOoE_6u73yOGOgBn0im8tE_dcUrIR74EYy_l8HKId7AvyY2OszmP1JrCkR6dLslS0; expires=Fri, 18-Nov-2016 06:11:07 GMT; path=/; HttpOnly
Set-Cookie: dnn_IsMobile=False; path=/; HttpOnly
Set-Cookie: .ASPXANONYMOUS=YrYcKYrviiUjmN7dSAd2DYWBO5W_Nj2yS_79eZ473OtallQXmOoE_6u73yOGOgBn0im8tE_dcUrIR74EYy_l8HKId7AvyY2OszmP1JrCkR6dLslS0; expires=Fri, 18-Nov-2016 06:11:07 GMT; path=/; HttpOnly
Set-Cookie: language=es-CO; path=/; HttpOnly
Set-Cookie: ARRAffinity=03cc22ac05b5cc76e788b382c1c33cccde1e727973fdb84dce1c542f8f1d9b46;Path=/;Domain=plcolabv2-pre.azurewebsites.net
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Bearer bad-credentials
Date: Fri, 09 Sep 2016 19:31:07 GMT
Content-Length: 0
Expires: -1
}}


Please, how can I get the results on first line, and store it on a variable? (
StatusCode: 401, ReasonPhrase: 'Unauthorized'
). When I post invalid user/pass, variable
response
have
null
value.

My code:
....

// Request body
byte[] byteData = Encoding.UTF8.GetBytes(jOneLogin);

using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
}

var results = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);

var crAccessToken = results.accessToken;
....


Maybe, is a simple question, answered in the past, but I can't find a specific post for that.

Thanks in advance.

dbc dbc
Answer Source

As you are using HttpClient, you can just check HttpResponseMessage.IsSuccessStatusCode before calling JsonConvert.DeserializeObject(). See this answer for an example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download