自定义对验证错误的自动响应 [英] Customize automatic response on validation error
问题描述
使用asp.net core 2.1,当发生验证错误时,ApiController将自动以400 BadRequest进行响应.
如何更改/修改发送回客户端的响应(json-body)?有某种中间件吗?
我正在使用FluentValidation验证发送到控制器的参数,但是我对收到的响应不满意.看起来像
{
"Url": [
"'Url' must not be empty.",
"'Url' should not be empty."
]
}
我想更改响应,因为我们有一些附加到响应的默认值.所以应该看起来像
{
"code": 400,
"request_id": "dfdfddf",
"messages": [
"'Url' must not be empty.",
"'Url' should not be empty."
]
}
InvalidModelStateResponseFactory
属性,其类型为Func<ActionContext, IActionResult>
. >
这是一个示例实现:
apiBehaviorOptions.InvalidModelStateResponseFactory = actionContext => {
return new BadRequestObjectResult(new {
Code = 400,
Request_Id = "dfdfddf",
Messages = actionContext.ModelState.Values.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
});
};
传入的 With asp.net core 2.1 an ApiController will automatically respond with a 400 BadRequest when validation errors occur. How can I change/modify the response (json-body) that is sent back to the client? Is there some kind of middleware? I´m using FluentValidation to validate the parameters sent to my controller, but I am not happy with the response that I am get. It looks like I want to change the response, cause we have some default values that we attach to responses. So it should look like
The Here's an example implementation: The incoming To use this implementation, configure the
这篇关于自定义对验证错误的自动响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!ModelState
和 serviceCollection.Configure<ApiBehaviorOptions>(apiBehaviorOptions =>
apiBehaviorOptions.InvalidModelStateResponseFactory = ...
);
{
"Url": [
"'Url' must not be empty.",
"'Url' should not be empty."
]
}
{
"code": 400,
"request_id": "dfdfddf",
"messages": [
"'Url' must not be empty.",
"'Url' should not be empty."
]
}
ApiBehaviorOptions
class allows for the generation of ModelState
responses to be customised via its InvalidModelStateResponseFactory
property, which is of type Func<ActionContext, IActionResult>
.apiBehaviorOptions.InvalidModelStateResponseFactory = actionContext => {
return new BadRequestObjectResult(new {
Code = 400,
Request_Id = "dfdfddf",
Messages = actionContext.ModelState.Values.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage)
});
};
ActionContext
instance provides both ModelState
and HttpContext
properties for the active request, which contains everything I expect you could need. I'm not sure where your request_id
value is coming from, so I've left that as your static example.ApiBehaviorOptions
instance in ConfigureServices
:serviceCollection.Configure<ApiBehaviorOptions>(apiBehaviorOptions =>
apiBehaviorOptions.InvalidModelStateResponseFactory = ...
);