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 = ...
);
Consider creating of custom action filer, e.g.:
public class CustomValidationResponseActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errors = new List<string>();
foreach (var modelState in context.ModelState.Values)
{
foreach (var error in modelState.Errors)
{
errors.Add(error.ErrorMessage);
}
}
var responseObj = new
{
code = 400,
request_id = "dfdfddf",
messages = errors
};
context.Result = new JsonResult(responseObj)
{
StatusCode = 400
};
}
}
public void OnActionExecuted(ActionExecutedContext context)
{ }
}
You can register it in ConfigureServices
:
services.AddMvc(options =>
{
options.Filters.Add(new CustomValidationResponseActionFilter());
});