Apis can be easily implemented with the power of Azure Functions, and when you need to validate models, Fluent Validation comes in handy, helping us to validate models elegantly. Fluent Validation is a validation library available as a NuGet package, that can be easily implemented by developers. It uses a fluent API that leverages lambda expressions to validate rules.
Check my previous article if you want more details about the Fluent Validation in .NET 6. Otherwise, stick to this article as I’m going straight to coding.
Creating the project
On Visual Studio 2022 create a new Functions project. Make sure you get the settings right.
If you are like me and like Dependency Injection, check the PlayGoKids repository for this example.
You are going to notice that I have deleted the out-of-the-box Functions1.cs, added Startup.cs and created other classes for Products. The solution looks like this:
The NuGet packages FluentValidation and FluentValidation.AspNetCore are assigned to the project.
On Startup.cs the FluentValidation library is hooked up to Service Collection. This is possible because of the NuGet package FluentValidation.AspNetCore.
publicclassProductViewModelValidator:AbstractValidator<ProductViewModel>{publicProductViewModelValidator(){RuleFor(model=>model.Name).NotNull().NotEmpty().WithMessage("Please specify a name");RuleFor(model=>model.Sku).NotNull().NotEmpty().Length(3,10);RuleFor(model=>model.Quantity).GreaterThanOrEqualTo(0);RuleFor(model=>model.Price).NotEqual(0).When(model=>model.Quantity>0).WithMessage("Please specify a price");}}
The rules are simple to understand, for more details please check my previous article.
The Open Api
The solution has a POST endpoint (with OpenApi attributes) that allows users to submit a Product.
The Fluent Validation is executed on the request, and in case it fails, it returns a BadRequest.
Join the conversation! Share your thoughts and connect with other readers.