未授权时管理来自 Newtonsoft.Json 的返回码

Managing returncode from Newtonsoft.Json when not authorized

我们在 JWT 门户上使用了一个实施登录。 当我 post 一个有效的 user/pass 时,我们有一个令牌 ok。但是当我 post 无效 user/pass 时,响应具有以下格式:

{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
}}

请问如何在第一行获取结果并将其存储在变量中? (StatusCode: 401, ReasonPhrase: 'Unauthorized')。当我post无效user/pass时,变量responsenull值。

我的代码: ....

        // 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;
        ....

也许,这是一个简单的问题,过去已经回答过,但我找不到具体的 post。

提前致谢。

因为您正在使用 HttpClient, you can just check HttpResponseMessage.IsSuccessStatusCode before calling JsonConvert.DeserializeObject(). See 作为示例。