【发布时间】:2022-01-20 04:09:23
【问题描述】:
我有 asp.net web api 应用程序。当我尝试向我的 api 发送带有无效 Json 的请求时,响应是错误请求。
如何更改响应客户端消息?
我尝试InvalidModelStateResponseFactory 和ModelBindingMessageProvider
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; }
}
请求如下所示,Id 和 DateTimeOffset 类型无效
{
"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 验证器生成的响应。