Handling .net’s model state with ValidationFilter attribute

This is a simple ValidationFilter class which you can attach to any .net controller action method:

What it provides is a “one-line” way to handle invalid model states. For example – instead of doing ModelState.IsValid check on each POST/PUT action, and then handling it manually again and again (by basically copying and pasting the same chunk of code all around your controllers) you can simply reuse the [ValidationFilter] attribute in front of your action and it will check whether the ModelState is valid. If it is, the action method will execute whatever code it has inside of it, and if it’s not the WebAPI will respond with a 422 (Unprocessable Entity) together with the associated ModelState error messages.

For example if you had this model/action combination:

…and you didn’t send any data to the WebAPI in your POST request, this is the 422 response that you would get back:

This response can then be further parsed/handled by the client-side without problems.