0

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.

Gabms
  • 83
  • 1
  • 7
  • Assuming you're using `HttpClient`, can't you just check [`HttpResponseMessage.IsSuccessStatusCode`](https://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage.issuccessstatuscode(v=vs.118).aspx)? See [this answer](https://stackoverflow.com/questions/32569860/checking-if-httpstatuscode-represents-success-or-failure/32570068#32570068) for details. – dbc Sep 09 '16 at 19:58
  • Works for me. Thanks! I need to mark your question like accepted, but your answer is a comment. How can I do it? – Gabms Sep 09 '16 at 20:50

1 Answers1

1

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

dbc
  • 104,963
  • 20
  • 228
  • 340