问题描述
我有 .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-core
我尝试了以下但仍然相同的响应
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
ex)
backup_file --------delete---------current
|________(skip query)__________|
archive files
当我最后添加它时它起作用了