解析值时 HttpClient JsonReaderException 意外字符

HttpClient JsonReaderException unexpected character while parsing value

上下文 - 我们的代码

我们在重定向 API Http GET 调用时遇到错误。我在 Whosebug 上搜索了类似的问题,但它似乎不像我们的问题。

我们有一个简单的场景。我们的解决方案是作为 "gateway" 调用 API 的后端。

从我们的 angular 客户端,我们调用 /api/values,它必须重定向到 http://example.com:8080/api/values

所以我们开始了 .NET Core API 项目,我们尝试从 API 控制器简单地进行 API 客户端调用。

原文如下class:

namespace WebApplication2.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

然后我们将实际调用添加到我们的真实 API 中,如许多教程中所述。我们只想 return 我们从 API 得到的回应(格式见下文)。

// GET api/values
[HttpGet]
public async Task<String> Get()
{
    string retValue = "";
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://example.com:8000");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("/document/info/ab5846a1afe8ad12e46a4e60");
        if (response.IsSuccessStatusCode)
        {
            retValue = await response.Content.ReadAsAsync<string>();
        }
    }
    return retValue;
}

错误

An unhandled exception occurred while processing the request.

JsonReaderException: Unexpected character encountered while parsing value: {. Path '', line 2, position 1. ReadStringValue

我们的API正常反应,简单JSON

如果我用这条路线向我们的 API 发送邮递员,结果如下:

{
  "errorCode": 0,
  "docId": "ab5846a1afe8ad12e46a4e60",
  "status": 0
}

.NET 中得到的响应

{
   "version":{
      "major":1,
      "minor":1,
      "build":-1,
      "revision":-1,
      "majorRevision":-1,
      "minorRevision":-1
   },
   "content":{
      "headers":[
         {
            "key":"Content-Length",
            "value":[
               "78"
            ]
         },
         {
            "key":"Content-Type",
            "value":[
               "application/json"
            ]
         }
      ]
   },
   "statusCode":200,
   "reasonPhrase":"",
   "headers":[
      {
         "key":"Date",
         "value":[
            "Fri, 06 Jan 2017 12:54:31 GMT"
         ]
      }
   ],
   "requestMessage":{
      "version":{
         "major":1,
         "minor":1,
         "build":-1,
         "revision":-1,
         "majorRevision":-1,
         "minorRevision":-1
      },
      "content":null,
      "method":{
         "method":"GET"
      },
      "requestUri":"http://example.com:8000/document/info/ab5846a1afe8ad12e46a4e60",
      "headers":[
         {
            "key":"Accept",
            "value":[
               "application/json"
            ]
         }
      ],
      "properties":{

      }
   },
   "isSuccessStatusCode":true
}

好的,问题已通过定义响应模型解决。如

public class DocumentInfo
    {
        public int errorCode;
        public string docId;
        public int status;
    }

然后输入如下:

var retValue = new DocumentInfo();
retValue = await response.Content.ReadAsAsync<DocumentInfo>();

关于方法:

 public async Task<DocumentInfo> Get()

后续问题

有什么办法可以不强类型返回结果吗?如果它从远程 API 更改(例如,如果他们添加 "Owner" 属性),它会中断吗?

这一行就是问题所在

retValue = await response.Content.ReadAsAsync<string>();

带有 string 参数的 ReadAsAsync 泛型方法基本上是将 HttpResponseMessage 反序列化为字符串 .

改用ReadAsStringAsync

retValue = await response.Content.ReadAsStringAsync();

你应该会得到想要的结果。