.NET Core 2.1 Override Automatic Model Validation
Asked Answered
O

2

13

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.

Ohm answered 1/7, 2018 at 17:39 Comment(2)
It looks like you only need to remove the ApiController attribute. That would 'revert' the logic to the 'old' style.Macomber
@Macomber you are absolutely right. Silly of me for not thinking of that. Thanks!Ohm
A
19

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.

Alizaalizarin answered 25/7, 2018 at 15:18 Comment(2)
You save my life, I have been looking this code for a long timeFlagging
I also needed options.Filters.Add(typeof(ValidateModelAttribute)); in mvc options for this to work, see Daniel's answer.Rhyner
T
11

I was recently asked by a friend about this and my approach was to replace the default ModalStateInvalidFilter by a custom one.

In my test I've implemented the suggestion from here and then:

services.AddMvc(options =>
{
    options.Filters.Add(typeof(ValidateModelAttribute));
});


services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });
Tekla answered 1/12, 2018 at 17:34 Comment(1)
thanks for sharing this as well as the blog post :)Vassily

© 2022 - 2024 — McMap. All rights reserved.