DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core

Trending

  • Driving DevOps With Smart, Scalable Testing
  • Proactive Security in Distributed Systems: A Developer’s Approach
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  1. DZone
  2. Coding
  3. Frameworks
  4. Model Validation Using FluentValidation in ASP.NET

Model Validation Using FluentValidation in ASP.NET

One requirement for any good API is the ability to validate input relying on different business rules. In this post, we'll look at model validation in ASP.NET

By 
Andrew Kulta user avatar
Andrew Kulta
·
Feb. 21, 22 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
7.5K Views

Join the DZone community and get the full member experience.

Join For Free

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:

C#
 
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.

C#
 
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.

C#
 
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.

C#
 
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.

ASP.NET

Published at DZone with permission of Andrew Kulta. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!