In this article, we will learn how to implement FluentValidation to our model classes in ASP.NET core 7 with minimal APIs.
We have already discussed what is minimal API in .Net Core. While working with an application, validation plays an important role. It helps us validate our data and ensure we insert the correct data into the database.
There is no in-built support to validate the model in the minimal APIs (unlike what we used to have in ASP.NET Core MVC and Razor Pages). Hence, we need to write custom code to validate the models in our minimal API applications.
FluentValidation validation helps us validate our model when working with DotNet Core 7.0 application.
To utilize the functionality of FluentValidation, we need to install the FluentValidation library from the NuGet package manager. FluentValidation uses the fluent API and the lambda expression to create the data validation rules for a model. Below is the command to install the FluentValidation package
PM> Install-Package FluentValidation.AspNetCore
Let's understand fluentValidation practically
First, let's create an ASP.NET core application. So to create it, open VS 2022, select the ASP.NET Core Web API template and click Next.
Now give the project name 'FluentValidationInAspCore' and click Next.
Now select the Framework as .NET 7.0 and click Next.
Once you click Next, it will create an ASP.NET core application. Now go to Nuget Package Manager by right-clicking on the project solution.
Once you click on Manage Nuget packages, a new window will appear. Search for "FluentValidation.AspNetCore" and install it.
Now right-click on the project and create a Student Model class like below
Create the StudentValidator class
To implement the required field or other validation to the student Model class, we need to create a StudentValidation class. Here we can create our custom validation by inheriting StudentValidation class from AbstractValidator, like below.
Now create an interface IstudentBuilder class and write the below code to add the student information.
Now create a studentBuilder class and inherit it from the Istudentbuilder interface and implement the method.
Now we need to register our validator class and builder classes to Program.cs like below
Create the HttpPost endpoint in the Program.cs
Write the below code to create the HTTP POST endpoint in minimal API.
Now run your application on swagger. Click on the Try it out button.
Without giving any value, if you run it, you will see a validation error like below.
So, these are the step to implement model validation to Minimal API in asp.net core 7.0.
Source Code: https://github.com/TheDotNetOffice/FluentValidation-in-minimal-APIs-in-ASP.NET-Core-7.0
-----------------------------------------------------------
EmoticonEmoticon