Creating validation filters for WebAPI

Posted: October 24, 2019  |  Categories: WebAPI
Tags:

While working in the development of new APIs for the organization that I work for, it came up with a couple of requirements to validate the input that the API consumer was passing in the request.

There are several ways of doing this, but in the WebAPI world, something that is reusable was the focus here. For that, I used Action Filters and Parameter Bindings. Below I’m going to show how I implement both of them.

WebAPI Action Filter

In my first validation requirements, I would have to look into the body of the Http requests and validate that some of the fields being passed as a JSON.

To do so using an Action Filter we need to create a new class that derives from the ActionFilterAttribute class as below:

In this class I wanted to be able to perform validations using regular expressions. I also wanted to add validations on the size of the strings in those Http JSON requests, so I updated the implementation to be as this:

There one part missing here, but before going there, let me show how to apply this Action Filter in the WebAPI controller.

Now that I’m applying the attribute to the operation in the WebAPI controller, let’s complete the code to get the value from Http request and validate the information we want from it.

As you can see, this is a very powerful feature from WebAPI where we can implement common behaviors in our applications by applying Action Filters.

If you want to learn more about that, just go to the following Microsoft documentations about it:

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.0

WebAPI HttpParameterBinding

The previous code, works well when we have an object being passed in the body of an Http request and you want to apply the Action Filter on the WebAPI controller operation. If you want to apply the same kind of validation, but on the individual parameters of the WebAPI controller operation, you need to work with Parameter Bindings.

To work with this structure you need to implement the following classes:

The code above is not complete, but since I found this solution in StackFlow, here is the thread where you can get the full code and adapt to your scenarios.

https://stackoverflow.com/questions/28736067/web-api-single-string-parameter-validation-using-validation-attributes

Now, that the classes are implemented, you can apply them in your parameters as below:

Summary

For those that are working with WebAPI, using Action Filter and Parameter Bindings is a very powerful way of having common behavior shared among all your APIs.

Author: Alessandro Moura

Certified BizTalk, Mulesoft, TOGAF and Azure. Integration Specialist. Solutions Architect.

1 thought on “Creating validation filters for WebAPI”

Leave a Reply

turbo360

Back to Top