One of the requirements for a good API is the ability to validate input relying on different business rules. As developers, we always care about validation when getting any data from clients.
The Source code used in the article you can find in our GitHub repository.
ASP.NET has a built-in mechanism to validate input payloads on the API level. But it’s limited when we are trying to validate input payload with custom business rules. We can move validation inside our business layer and apply our custom validation for input models. Choosing this decision, we are making controllers thin. It just makes a proper model binding and invokes the required service method. Functional tests could cover such behavior, and we don’t need to write unit tests for such thin controller actions.
We can write our custom validation rules, invent a new validation tool and come to a not so handy code with many ifs. in this case, FluentValidation comes into play.
FluentValidation is a library for building strongly-typed validation rules.
Let’s start diving into the code:
public class ApiController : BaseController
The controller becomes clean and straightforward. ASP.NET still applies validation for model fields, but business validation happens in the service layer.
public class Service
The first thing we want to do before starting the implementation for business logic is to apply our validation to the input payload. Each payload requires a proper validator, and it causes a situation when we need to inject many validators into our service to validate input models. It’s better to avoid such cases and introduce another service responsible for model validation only, and it hides all complexity of business validation from other services.
public class ValidationService
We have a proper structure for validation and are ready to add model validators. FluentValidation gives us a base class AbstractValidator
public class CreateRequestValidator : AbstractValidator<CreateRequest>
We got a clean way to separate validation for input requests into small classes. We can write complex validators that rely on business rules, and it’s simple for us to test validators as a small independent part of the solution.