Simple ModelState Extension

Something might be out there like this already but I recently found myself needing to not only validate a model that has been posted or put into an API but also be able to easily roll up those validation errors and ship them back.  I know there are lots of ways to accomplish this but here was my approach.

First, start with the model and a validation

Super simple I know but we’ve got a basic DTO that has a requirement to always carry the Name property.

And we can have a controller that takes this model and validates it.

This is great.  We can do something interesting when we receive bad input.

But my requirement was to have my API return a list of all of the errors that came off the Model.  So my approach was to extend the ModelState class.  What this gave me the opportunity to do is iterate the errors, put them into a container and the return that as part of the status 400 response to the client so that they can do something interesting with the output.

So here is the extension method

Very straightforward.  What I’m doing here is looking at the ModelStateDictionary, looping the values and looking for errors.  If errors exist for  a specific value then I add the string error message onto a List<string> and then at the end return a container object that holds the errors.  If I wanted, I could put more on the ValidationResponse class but this is just an example so I believe you could further extend the concept.

The response class looks like this

Now your controller action looks like this.

You’ll have a response which is a 400 with an array of errors.

And your finished.  Hope this helps as you think about validating API input


About the author

Ben Pyle is a software developer who enjoys solving problems and delighting customers with right quality software. He's a husband, father to 2 boys and avid golfer. In his free time he enjoys reading, playing lots of golf and hanging out with his family doing whatever they are into.

Leave a Reply

Your email address will not be published. Required fields are marked *