{
"errors": {
"price": [
"Could not convert string to decimal: dasdfasdf. Path 'price', line 3, position 22."
],
"userId": [
"Could not convert string to integer: hsad. Path 'userId', line 6, position 27."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|bcaa98d957e1c04181000489a0bc4950.9753735a_"
}
我尝试过自定义模型绑定器,但我需要这个用于模型中的特定属性。我也尝试了JsonConvert与属性,但无法找到在模型状态下注入错误消息的方法
您可以通过配置InvalidModelStateResponseFactory
的ApiBehaviorOptions
来自定义ApiController的ModelState验证器响应,如下所示:
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
var errors = actionContext.ModelState
.Where(e => e.Value.Errors.Count > 0)
.Select(e => new Error
{
Name = e.Key,
Message = e.Value.Errors.First().ErrorMessage
}).ToArray();
return new BadRequestObjectResult(errors);
}
});
此外,您可以阅读有关ApiController行为here的更多信息。