{
"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_"
}
我试过自定义模型 Binder ,但我需要它用于模型中的特定属性。我还尝试了 JsonConvert 的属性,但找不到在模型状态中注入(inject)错误消息的方法
最佳答案
您可以通过配置 ApiBehaviorOptions
的 InvalidModelStateResponseFactory
来自定义 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 .
关于c# - 有没有办法为默认模型绑定(bind)错误构建自定义错误消息,想要摆脱消息中的行和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653921/