【问题标题】:Managing returncode from Newtonsoft.Json when not authorized未授权时管理来自 Newtonsoft.Json 的返回码
【发布时间】:2016-09-09 19:45:43
【问题描述】:

我们在 JWT 门户上使用了实现登录。 当我发布有效的用户/通行证时,我们有一个令牌。但是当我发布无效的用户/通行证时,响应具有以下格式:

{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')。当我发布无效用户/密码时,变量response 具有null 值。

我的代码: ....

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

也许,是一个简单的问题,过去曾回答过,但我找不到具体的帖子。

提前致谢。

【问题讨论】:

标签: c# json json.net dotnet-httpclient


【解决方案1】:

当您使用HttpClient 时,您可以在调用JsonConvert.DeserializeObject() 之前检查HttpResponseMessage.IsSuccessStatusCode。示例见this answer

【讨论】:

  • 谢谢@dbc。完成IsSuccessStatusCodeStatusCodeReasonPhrase
猜你喜欢
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 1970-01-01
相关资源
最近更新 更多