d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

Model Validation Using FluentValidation in ASP.NET

The source code used in the article can be found in our GitHub repository.

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.

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 and 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
{
    private readonly IService _service;
    
    public TimeEntryController(IService service)
    {
        _service = service;
    }


    [ProducesResponseType(typeof(Response), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ExceptionModel), StatusCodes.Status400BadRequest)]
    [HttpPost]
    public async Task<ObjectResult> CreateAsync([FromBody] CreateRequest request)
    {
        var response = await this._service.CreateAsync(request);
        return this.Ok(response);
    }
}

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
{
    private readonly IValidationService _validationService;
    
    public TimeEntryService(IValidationService validationService)
    {
        _validationService = validationService;
    }

    public async Task<Response> CreateAsync(CreateRequest request)
    {
        this._validationService.EnsureValid(request);
        // Implementation
        return new Response();
    }

}

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
{
    private readonly IDictionary<Type, Type> _validators;
    private readonly IServiceProvider _serviceProvider;

    public ValidationService(IServiceProvider serviceProvider)
    {
        this._serviceProvider = serviceProvider;
        this._validators = new Dictionary<Type, Type>
        {
            { typeof(CreateRequest), typeof(CreateRequestValidator) },
        };
    }

    private AbstractValidator<T> GetValidator<T>()
    {
        var modelType = typeof(T);
        var hasValidator = this._validators.ContainsKey(modelType);
        if (hasValidator == false)
        {
            throw new Exception("Missing validator");
        }

        var validatorType = this._validators[modelType];
        var validator = _serviceProvider.GetService(validatorType) as AbstractValidator<T>;
        return validator;
    }

    public void EnsureValid<T>(T model)
    {
        var validator = this.GetValidator<T>();
        var result = validator.Validate(model);
        if (result.IsValid == false)
        {
            throw new Exception(result.ToString());
        }
    }
}

We have a proper structure for validation and are ready to add model validators. FluentValidation gives us a base class AbstractValidator<T> to inherit for our custom validators.

public class CreateRequestValidator : AbstractValidator<CreateRequest>
{
    public CreateRequestValidator()
    {
        RuleFor(r => r.Name).Required();
        RuleFor(r => r.Date.ToUniversalTime()).LessThan(DateTime.UtcNow);
    }
}

Conclusion

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.

Any questions or comments? Ping me on LinkedIn or comment below.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this