Validate the model state globally in .Net Core MVC: .Net Core Quick posts

Session in .Net Core1 (4)

You can find all of my  .Net core posts here.

In this post, we will see an awesome feature of .Net Core which will make the developer’s life bit easy.

We are talking about the Auto-validation of the models in .Net Core.

I remember putting ModelState.IsValid check in almost all POST, PUT, DELETE etc action methods of a controller. This check was used to check whether the Model is having any errors or not.

So if IsValid returns false then Model contains some validation error and the controller would not allow the model to pass into the controller.

If you are from MVC background then you would be quite familiar with the below code:

if (!ModelState.IsValid)
// return bad request or errors or redirect it to somewhere

As we can see above, we have to put this check into many actions and many controllers. But what if we can add this check globally?

I know we can create some custom attributes and we can add those attributes above the action methods or the controllers. But what if we can add this validation check globally without putting the attributes above the actions or controllers?

Interesting right?

It is very much possible in .Net Core. We just need to add few lines of code which will work for all the controllers and actions.

Add Custom filter class

Let us add the Custom filter class, we will name it as ValidateMyModelAttribute as below:

public class ValidateMyModelAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
if (!context.ModelState.IsValid)
context.Result = new BadRequestObjectResult(context.ModelState); // it returns 400 with the error

Here the filter would return BadRequest if the Model is not valid.

Add custom filter globally

Next step is to add this custom filter globally in Startup.cs class. We will add this filter to the ConfigureService method of the class as shown below:

public void ConfigureServices(IServiceCollection services)
services.AddMvc(options =>

That is it. Now the model will be validated in all those required action methods hence no more headache of adding same repetitive code in all action methods.

Hope it helps.


6 thoughts on “Validate the model state globally in .Net Core MVC: .Net Core Quick posts

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s