Custom response on model validation error

In ASP.NET core, when returning a BadRequest, you would usually include some error message or code inside.
E.g. 

return BadRequest(new { error = "Not good" })


When the view model has an error verified according to the data annotation attribute, the result might be in a different format.
To keep the the same structure for the returned object add this to the startup.cs file:

services.AddControllers((options) =>
{
})
.ConfigureApiBehaviorOptions((options) =>
{
     options.InvalidModelStateResponseFactory =
                   context =>
                    {
                        var error = context.ModelState.FirstOrDefault().Value.Errors.FirstOrDefault()?.ErrorMessage;
                        return new BadRequestObjectResult(new { error });
                    };
})

Post a Comment

Previous Post Next Post