Share via


Avoid duplication of ModelState.IsValid in ASP.NET Core

Generally, whenever something is to be saved to the database or to any other place, as a best practice almost everyone use to validate the state of the model. So, if state of model is valid, we proceed and if model state is invalid, we handle it as a bad request. This looks something like this:

1.If(!ModelState.IsValid)
2.{
3.    // create bad request object 
4.}

So, all these were done by using the IsValid property.

Problem Statement
Now what if we have to perform the same validation for all the models? Are we going to write the same validation in each and every controller?

Of course, No.

Solution
Rather than duplicating the same code in each and every controller, we can create a global filter. This global filter has few methods, but for our purpose we can go with OnActionExecuting.

01.public class  ValidateModelStateFilter : ActionFilterAttribute
02.{
03.    public override  void OnActionExecuting(ActionExecutingContext context)
04.    {
05.        if (!context.ModelState.IsValid)
06.        {
07.            context.Result = new  BadRequestObjectResult(context.ModelState);
08.        }
09.    }
10.}

Next is to update ConfigureServices method under Startup class:

1.services.AddMvcCore(options =>
2.  {
3.        options.Filters.Add(typeof(ValidateModelFilter));
4. })

Once above changes are done, we need not to repeat the same ModelState validation check in each and every controller.
Hope this tip would be helpful.