【问题标题】:dotnet invalid json body client messagedotnet 无效的 json 正文客户端消息
【发布时间】:2022-01-20 04:09:23
【问题描述】:

我有 asp.net web api 应用程序。当我尝试向我的 api 发送带有无效 Json 的请求时,响应是错误请求。 如何更改响应客户端消息? 我尝试InvalidModelStateResponseFactoryModelBindingMessageProvider ASP.NET Core Model Binding Error Messages Localization

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpPost]
    public void Post([FromBody] ForTestJson request)
    {
        //some operation after validation
    }

}

public class ForTestJson
{
    public long Id { get; set; }
    public string Name { get; set; }
    public DateTimeOffset DateTimeOffset { get; set; }
}

请求如下所示,IdDateTimeOffset 类型无效

{
  "id": "aaa",
  "name": "string",
  "dateTimeOffset": "bbb"
}

回应是

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-a3ab5818c8cdc45073d5f5c8941887e9-3fcff0b267c68057-00",
  "errors": {
    "request": [
      "The request field is required."
    ],
    "$.id": [
      "The JSON value could not be converted to System.Int64. Path: $.id | LineNumber: 1 | BytePositionInLine: 13."
    ]
  }
}

我想将“无法将 JSON 值转换为...”更改为另一条消息

【问题讨论】:

  • 你不能分享验证并返回响应的代码吗?
  • 我创建了新的 Web API 项目并且我不使用任何自定义验证器。默认 asp.net 验证器生成的响应。

标签: c# .net


【解决方案1】:

您的请求正文无法反序列化为ForTestJson 的实例,因为请求中iddateTimeOffset 属性的数据类型与ForTestJson 类中相应属性的数据类型不匹配。

如果您想返回不同的错误消息,您可以更改Post 方法的签名以接受string 而不是ForTestJson 实例,然后在Post 方法中编写您自己的代码尝试将字符串从 JSON 反序列化为 ForTestJson 实例,捕获反序列化期间引发的任何异常,解释异常并从中构建您自己的错误消息。

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 2021-03-15
    • 2013-03-18
    • 1970-01-01
    • 2012-11-02
    • 2014-01-20
    • 1970-01-01
    • 2014-08-30
    • 2013-02-21
    相关资源
    最近更新 更多