输入为什么不能作为JSON字符串C#有效?

时间:2018-09-20 08:51:13

标签: c# json rest parsing httpclient

我正在使用ASP.NET应用程序,并且正在我的类库中发送请求(REST API)。我有一个测试应用程序(控制台应用程序),其中相同的代码可以完美地工作而没有任何错误,但是在我们客户的ASP.NET应用程序中却出错了。

我在测试应用程序中执行以下操作:

using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL))
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    //headers
    request.Headers.Add("Authorization", "Bearer " + tokenResponse.AccessToken);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    RequestObject createdRequest = CreateRequest();
    string json = JsonConvert.SerializeObject(createdRequest);

    StringContent stringContent =
        new StringContent(
            json,
            Encoding.UTF8,
            "application/json");

    //body (content) of the request
    request.Content = stringContent;

    //sending the request through a POST method asynchronously
    using (HttpResponseMessage httpResponse = await client.SendAsync(request))
    {
        string stringContents = await httpResponse.Content.ReadAsStringAsync();
    }
} 

我在ASP.NET应用程序中运行同一段代码,但收到状态代码BadRequest,在string stringContents = await httpResponse.Content.ReadAsStringAsync();处显示:提供的输入无效,不能作为JSON字符串,不能解析。

下面的JSON对象是我用Console.WriteLine();打印出来的(由于隐私原因,我留下了许多属性):

{
  "MainObject":[
    {
      "Object1":{
        "prop1":"value",
        "prop2":"value",
        "prop3":"value",
        "prop4":"value",
        "prop5":"value",
        "prop6":"2018-09-20"
      },
      "Object2":{
        "prop1":"2822",
        "prop2":null,
        "prop3":100.0,
        "prop4":"value",
        "prop5":"value",
        "prop6":"value",
        "prop7":"value",
        "prop8":null,
        "prop9":null,
        "prop10":null,
        "prop12":null,
        "prop13":null,
        "prop14":null,
        "prop15":2,
        "prop16":0.0,
        "prop17":0.0,
        "prop18":"value"
      }
    }
  ]
}

有人能看到我做错了吗?

0 个答案:

没有答案