Integrating FluentValidation with ASP.NET Web API
In short, we dislike the Validation that comes with MVC and, now, Web Api. No need to go into why here, but things like Attribute dependencies and its clunky API are bad …. m’kay.
Fluent Validation is a popular, open-source, fluent-API based validation engine for .Net that we prefer over the default validation. There are several ways of integrating Web Api with Fluent Validations. Some of those are explained here and here.
Initially, we went with a custom implementation of the latter since it hooks right into the Model property of ActionContext of an ActionFilter. This is nice because the Validation action filter would only need to verify that the ModelState.IsValid is true, or else, return an HTTP Bad Request Response (400) with the error messages.
However, we cringed at bringing a custom implementation of this library that includes a lot of extra artifacts and seems to no longer be active.
At one point, we realized that we could hook right into the ArgumentsProperty of the ActionContext. In this case, we can ask the Dependency Injection Container (we use StrucutreMap) for the validator for the type, then execute the validation.
Although we lose the nice ModelState.IsValid hook, we make it up by having a less-magical, more explicit implementation for validation that is easier to maintain and debug.
In order to get the container to get us the right Validator for the type, we need to register all types that Implement the “AbstractValidator<>” interface.
By the way, these Validators are also easily unit testable.
All the necessary, simplified code is found below: