ASP.NET Core 2 – Global Model validation

How we (some of us?) do Model validation right now

We, developers, use a lot of repetitive code in our ASP.NET (Core) Web API / MVC actions. Inside of our controller actions we usually check if the model is valid by using ModelState property available on MVC’s base controller class:

The bad thing about is that we repeat this piece of code throughout a lot of our actions.


How we could do it

We can make a global filter attribute to handle this for us when action is executing:

And then we can let MVC know that we want to use this filter, inside of our ConfigureServices in Startup class:

With these changes applied, we don’t have to do manual checks of ModelState property in our controllers.


How it should be done

We shouldn’t be doing this at all! It should be done by the framework itself. And, yes, this is happening. With ASP.NET Core 2.1 this will be done for us.

Why wasn’t this done before? Good question. However, another good question is why most of us did not suggest this feature or made a PR for it?

Thanks for reading!

Ibrahim Šuta

Software Engineer, Mentor and Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js. Experienced in MeteorJS, Node.js, ASP.NET, Windows Forms and Web Forms as well.