Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model State Validation in Web API

I have a custom model validator to validate and return custom validation messages.

public void Validate(Object instance) {
                // Perfom validations and thow exceptions if any
                   throw new ValidationException();
               }

Now, I want to validate each coming request using my custom validator.
Middleware and Fitlers have httpcontext object and I am supposed to read the request body, deserailize and then call my custom validator to perform validations.
I have suppressed the default automatic http 400 response.

Is there any proper way to call custom validator before each request to Web API?

like image 882
rashidali Avatar asked Mar 11 '26 15:03

rashidali


1 Answers

When [ApiController] attribute is applied ,ASP.NET Core automatically handles model validation errors by returning a 400 Bad Request with ModelState as the response body :

Automatic HTTP 400 responses

To disable the automatic 400 behavior, set the SuppressModelStateInvalidFilter property to true :

services.AddControllers()
    .ConfigureApiBehaviorOptions(options => 
    {   
        options.SuppressModelStateInvalidFilter = true;     
    });

Then you can create globally action filter to check the ModelState.IsValid and add your custom model validation ,something like :

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

And register it globally to apply the filter to each request .

like image 150
Nan Yu Avatar answered Mar 14 '26 03:03

Nan Yu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!