ASP.NET Web API 自定义数据类型错误时的错误消息

问题描述 投票:0回答:1

我有一个控制器,可以接受来自请求正文的数据

[HttpPatch("update-name")]
public async Task<IActionResult> UpdateName([FromBody] UpdateNameData data)
{
    ...
}
public class UpdateNameData
{
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; } = string.Empty;
}

当我发送

{"name": 1}
时,API 返回此错误:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "data": [
      "The data field is required."
    ],
    "$.name": [
      "The JSON value could not be converted to System.String. Path: $.name | LineNumber: 1 | BytePositionInLine: 10."
    ]
  },
  "traceId": "00-4cb41bb3f51e5253c5591ead5fccf96a-ea1c751ebed4be5b-00"
}

如何才能在用户发送错误类型时返回自定义错误消息?

c# asp.net-core validation asp.net-core-webapi
1个回答
0
投票

您必须创建一个自定义处理程序来处理无效的模型状态,请参阅这篇文章以获得一个很好的示例:在 web api .net core 3.1 中传递 int 而不是 string 时出现 400 badrequest

请注意,所有无效数据响应都会返回此信息

© www.soinside.com 2019 - 2024. All rights reserved.