data-annotations - 我们可以在 asp.net core 3.1 中覆盖数据注释响应的任何方式
问题描述
我有.net core 3.1 web api 项目。我已经在我的模型上进行了一些数据注释验证。我对验证的回应就像
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|41a37de5-4212fb57b7a19a61.",
"errors": {
"fk_entity_id": [
"Please enter a value bigger than 0"
]
}
}
我可以以任何方式覆盖该响应,例如
{
"success": "failed",
"message": "validation error occured",
"errors": {
"fk_entity_id": [
"Please enter a value bigger than 0"
]
}
}
找到一篇文章,但似乎与 asp.net core 旧版本有关 https://www.c-sharpcorner.com/blogs/customizing-model-validation-response-resulting-as-http-400-in-net-核
我尝试了以下但仍然相同的响应
private void CustomValidationResponse(IServiceCollection services)
{
services.Configure<ApiBehaviorOptions>(
options => options.InvalidModelStateResponseFactory = actionContext =>
{
return CustomErrorResponse(actionContext);
}
);
}
private BadRequestObjectResult CustomErrorResponse(ActionContext actionContext)
{
var errorRecordList = actionContext.ModelState
.Where(modelError => modelError.Value.Errors.Count > 0)
.Select(modelError => new Error
{
ErrorField = modelError.Key,
ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage
}).ToList();
return new BadRequestObjectResult(new
{
success = "failed",
message = "Validation error occured",
errors = errorRecordList
});
}
解决方案
问题是在里面放置 CustomValidationResponse
public void ConfigureServices(IServiceCollection services)
当我最后添加它时,它起作用了
推荐阅读
- python - 根据使用另一列的正则表达式提取的内容,有条件地在 spark 数据框中填充新列
- excel - 这个 Excel 模板中的图表数据在哪里?
- ruby - 为什么 () 在 Ruby 中返回 nil?
- c++ - 跨命名空间的基于 SFINAE 的运算符重载
- ios - 从ios中firebase上的特定文件夹下载所有图像
- javascript - 如何对两个数组的值进行累加和求和?
- amazon-web-services - 超时 SSH 到公共 AWS VPC 子网(带公共 IP、到 igw 的路由表、NACL 允许所有、安全组允许 SSH 等)
- c++ - 如何将获取的字符串数据转换为字符数组?
- react-native - Expo Project 无法在模拟器上启动
- php - Searching mysql database that has over 3 mil records