How do I customize ASP.Net Core model binding errors?
Solution 1:
It's worth mentioning that ASP.NET Core 2.1 added the [ApiController]
attribute, which among other things, automatically handles model validation errors by returning a BadRequestObjectResult
with ModelState
passed in. In other words, if you decorate your controllers with that attribute, you no longer need to do the if (!ModelState.IsValid)
check.
Additionally, the functionality is also extensible. In Startup
, you can add:
services.Configure<ApiBehaviorOptions>(o =>
{
o.InvalidModelStateResponseFactory = actionContext =>
new BadRequestObjectResult(actionContext.ModelState);
});
The above is just what already happens by default, but you can customize the lambda that InvalidModelStateResponseFactory
is set to in order to return whatever you like.