Search code examples
c#validation.net-core-2.1

.NET Core 2.1 Override Automatic Model Validation


In the latest .NET Core 2.1, an automatic validation for the model state validation is introduced (https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/#mvc).

Previously I could override the validation error response by the following code below:

public class ApiValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(new context.ModelState);
        }

    base.OnActionExecuting(context);
}

But now it no longer works. The validation errors is responded without entering the override method.

Anyone has any clue? Thanks.


Solution

  • If you'd like to keep using the ApiController attribute (which has other functions like disabling conventional routing and allowing model binding without adding [FromBody] parameter attributes), you might be able to do it via this in your Startup.cs file:

    services.Configure<ApiBehaviorOptions>(opt =>
    {
        opt.SuppressModelStateInvalidFilter = true;
    });
    

    That will make it so that if the ModelState is invalid it won't automatically return a 400 error.