自定义验证错误的自动响应

问题描述:

使用 asp.net core 2.1 时,ApiController 将在发生验证错误时自动响应 400 BadRequest.

With asp.net core 2.1 an ApiController will automatically respond with a 400 BadRequest when validation errors occur.

如何更改/修改发送回客户端的响应(json-body)?有什么中间件吗?

How can I change/modify the response (json-body) that is sent back to the client? Is there some kind of middleware?

我正在使用 FluentValidation 来验证发送到我的控制器的参数,但我对得到的响应并不满意.看起来像

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

{
    "Url": [
        "'Url' must not be empty.",
        "'Url' should not be empty."
    ]
}

我想更改响应,因为我们有一些附加到响应的默认值.所以它应该看起来像

I want to change the response, cause we have some default values that we attach to responses. So it should look like

{
    "code": 400,
    "request_id": "dfdfddf",
    "messages": [
        "'Url' must not be empty.",
        "'Url' should not be empty."
    ]
}

ApiBehaviorOptions 类允许通过其 InvalidModelStateResponseFactorya> 属性,类型为 Func.

这是一个示例实现:

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 实例同时提供 ModelStateHttpContext 活动请求的属性,其中包含我希望您可能需要的一切.我不确定您的 request_id 值来自哪里,因此我将其留作静态示例.

The incoming 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.

要使用此实现,请在 ConfigureServices 中配置 ApiBehaviorOptions 实例:

To use this implementation, configure the ApiBehaviorOptions instance in ConfigureServices:

serviceCollection.Configure<ApiBehaviorOptions>(apiBehaviorOptions =>
    apiBehaviorOptions.InvalidModelStateResponseFactory = ...
);