【问题标题】:How to catch and handle invalid json exception with Newtonsoft json?如何使用 Newtonsoft json 捕获和处理无效的 json 异常?
【发布时间】:2020-03-31 09:39:26
【问题描述】:

我有模型:

 public class PushManyRequest
    {
        [JsonProperty("ids")]
        public List<string> Ids { get; set; } 
    }

对于我的控制器,我有以下签名:

 public async Task<IActionResult> PushMany([FromBody] PushManyRequest request)
        {
         ...
        }

如您所见,我正在尝试将请求映射到模型。而且方便易懂! 我可以添加[Required(ErrorMessage=&lt;message&gt;)] 属性,如果没有ids,我会给客户我自己的错误

但是如果客户传递给我无效的 JSON 怎么办?例如:

{
    "ids": [
    "123",
    "234"
    "235     <---------------------- invalid!!!
    ]

}

我会为客户回答类似的问题:

{
  "status": "error",
  "description": [
    "Unterminated string. Expected delimiter: \". Path 'ids[991]', line 999, position 1.",
    "Unexpected end when deserializing array. Path 'ids[991]', line 999, position 1.",
    "Unexpected end when deserializing object. Path 'ids[991]', line 999, position 1."
  ]
}

如您所见,它非常不友好。这是我的内部解析错误,客户不需要知道它。我想返回类似的东西:

{
  "status": "error",
  "description": "Sorry, but your JSON is invalid. Please, check it and try again"
}

但我不明白我可以在哪里写它以及如何捕捉这种情况。有任何想法吗?谢谢!

【问题讨论】:

标签: c# asp.net-mvc asp.net-web-api json.net


【解决方案1】:

您应该查看模型状态。

if (!ModelState.IsValid)
{
  IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
  foreach (ModelError item in allErrors)
  {
        orderErrors += item.ErrorMessage;
        break;
  }
  using (var stream = new MemoryStream())
  {

      var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
      context.Request.InputStream.Seek(0, SeekOrigin.Begin);
      context.Request.InputStream.CopyTo(stream);
      string requestBody = Encoding.UTF8.GetString(stream.ToArray());

      log.write_to_log(requestBody, "null", "ModelState is not valid - " + orderErrors); //Saves to your log 

       return new HttpResponseMessage((HttpStatusCode)400);
   }
}
if (orderErrors != "")
{
      return new HttpResponseMessage((HttpStatusCode)400);
}
else 
{
     //Something happens
}

这样的事情应该可以工作^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多