Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

c# - Customize automatic response on validation error

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

{
    "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."
    ]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The ApiBehaviorOptions class allows for the generation of ModelState responses to be customised via its InvalidModelStateResponseFactory property, which is of type Func<ActionContext, IActionResult>.

Here's an example implementation:

apiBehaviorOptions.InvalidModelStateResponseFactory = actionContext => {
    return new BadRequestObjectResult(new {
        Code = 400,
        Request_Id = "dfdfddf",
        Messages = actionContext.ModelState.Values.SelectMany(x => x.Errors)
            .Select(x => x.ErrorMessage)
    });
};

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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...