Post

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 ModelStateproperty available on MVC’s base controller class:

https://gist.github.com/Ibro/8c5d2a02ef8426763d2f8faaa1592ce2

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:

https://gist.github.com/Ibro/9cd4125a40209b350e08140910d175a5

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

https://gist.github.com/Ibro/c5236aba559064500d139a77cdef1787

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!