Consistent Response Validation - Invalid Value for types & Business Rules in Web API

Fluent validation is a great library to perform validation on objects. Integrating fluent validation in .net core is very simple and minimal steps are described along with a way to make validation response consistent be it binding error or business validation error.

Steps
 1. Add a reference to NuGet package
     <PackageReference Include="FluentValidation.AspNetCore" Version="8.4.0" />
  1. Adding sample validator
Image for postImage for post

Person Validator
3. Validating Object
Image for post
Validating Object
This works fine and the correct error message is displayed.
Image for post
Fluent Validation Error Message response
However, consider the request where Date of Birth of person is passed as an invalid date. In this case, controller method gets null as input because of invalid type value during the model biding phase.
By default below error message is thrown if model state is validated in the controller method
Image for post
Default Model State Error
In this case, format of error message response is different from Fluent Validation Error message response. This will lead to inconsistent error response depending on the type of error, whether binding or business validation.
In order to make validation response consistent follow steps below:
  • Add ActionFilterAttribute to transform default binding error message to Fluent Validation error messages.
Image for post
Action Filter Attribute
  • Register ActionFilter in Startup.cs
Startup.cs
Below is the final output after using an action filter
Image for post
Binding error in FluentValation Error Format
Full code for the article can be found
Thanks!!!

Comments

Popular posts from this blog

Inversion of control in 3 layer architecture

Singleton pattern for logger class