Customize automatic response on validation error

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 = ...
);

Leave a Comment