rashidali
rashidali

Reputation: 330

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?

Upvotes: 3

Views: 6681

Answers (1)

Nan Yu
Nan Yu

Reputation: 27528

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 .

Upvotes: 14

Related Questions