When working with applications in ASP.NET Core 6 you will often wish to confirm your models to make sure that the data they contain comply with the pre-defined recognition guidelines. Enter design validation.We’ve discussed how
we can start with minimal APIs in an earlier short article. This post goes over how to use design validation in minimal APIs.To deal with the code examples provided in this post, you should have Visual Studio 2022 set up in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.
Produce an ASP.NET Core very little Web API task in Visual Studio 2022
First off, let’s produce an ASP.NET Core project in Visual Studio 2022. Following these actions will develop a new ASP.NET Core Web API 6 project in Visual Studio 2022:
- Introduce the Visual Studio 2022 IDE.
- Click “Create brand-new job.”
- In the “Produce new job” window, select “ASP.NET Core Web API” from the list of templates displayed.
- Click Next.
- In the “Configure your brand-new task” window, specify the name and place for the brand-new project.
- Optionally inspect the “Place solution and task in the same directory” check box, depending upon your preferences.
- Click Next.
- In the “Additional Information” window revealed next, uncheck the checkbox that states “Usage controllers …” considering that we’ll be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
- Ensure that the check boxes “Enable Docker,” “Set up for HTTPS,” and “Enable Open API Assistance” are unchecked as we will not be using any of those features here.
- Click Create.
This will create a new ASP.NET Core 6 Web API task in Visual Studio 2022. We’ll use this job to work with design validation in the subsequent sections of this article.What is model recognition? Why is it needed?Model validation is a method
used to validate model state, i.e., to identify if the data in the design conforms to the defined guidelines. Let us understand this with an example. Presume you have a design class called Product, in which among the fields is the Product Code. Now suppose you have actually specified a characteristic in the Product
class whereby the Product Code property can not have a worth that is longer than five characters. If you create an instance of this model class and designate more than five characters to the Product Code home, then design validation for this object will fail.There is no built-in assistance for design validation in minimal APIs(unlike in ASP.NET Core MVC and Razor Pages). For this reason, you will need to compose your own customized code to confirm the designs in your minimal API applications. Set Up the FluentValidation.AspNetCore NuGet bundle In this short article, we’ll utilize the FluentValidation validation library
, which is available as a NuGet bundle. FluentValidation utilizes
a fluent API and lambda expressions to develop data validation rules.Now add the FluentValidation.AspNetCore NuGet plan to your project. To do this, choose the project in the Option Explorer window, then right-click and select “Handle NuGet Packages. “In the NuGet Plan Manager window, look for the FluentValidation.AspNetCore package and install it.Alternatively, you can install the plan through the NuGet Bundle Supervisor console by entering the command shown below.PM > Install-Package FluentValidation.AspNetCore Develop the design class Produce a brand-new class called Product in a file with the exact same name and a.cs extension, and go into the following code in there. public class Product < This will work as the model class we will use for validation.Create the ProductValidator class Now suppose the
Item class requires a validator, i.e., a class that will confirm the properties of the Product class. You can develop a custom validator by extending the abstract class called AbstractValidator as
shown in the
code snippet given below.public class ProductValidator: AbstractValidator public ProductValidator()< Produce the IProductRepository user interface A repository is used in an application to persist information to a data shop such as a database or
. In this example, we will create an easy repository
that has a method called AddProduct, however
because we’re focusing on design validation here, we will not consist of the logic to include an item
record to the database.Create an interface called IProductRepository and go into the following code.
public user interface IProductRepository < Produce the ProductRepository class The ProductRepository class carries out the IProductRepository user interface as revealed below.public class ProductRepository: IProductRepository public void AddProduct(Product item) Register the validator and repository classes in Program.cs Register the ProductValidator and ProductRepository types
in the Program.cs file utilizing the following code.builder.Services.AddScoped();
builder.Services.AddScoped (); Develop a HttpPost endpoint in Program.cs Now compose the following code in the Program.cs file to develop a HttpPost endpoint.app.MapPost(“/ item”, async(IValidator validator, IProductRepository repository, Item item)
= > >(! validationResult.IsValid) repository.AddProduct(product); return Results.Created($”); Note how the parameters validator, repository, and item have actually been passed. The ValidateAsync method is contacted us to verify the item instance.Complete model validation example The total source code of the Program.cs file is provided listed below for your reference.using FluentValidation; var contractor=WebApplication.CreateBuilder (args);// Add services to the container.builder.Services.AddScoped (); builder.Services.AddScoped(); var app= builder.Build( ); // Configure the HTTP request pipeline.app.MapPost(“/ product”, async(IValidator validator, IProductRepository repository,
Product item)=> var validationResult=await validator.ValidateAsync (product);
and invoke the HttpPost endpoint from Postman to see design validation in action.
Figure 1 reveals the output upon validation of the design. Note the mistake messages
in the reaction.< img alt="model
validation aspnet core”width=”1200″height=”693″src =”https://images.idgesg.net/images/article/2022/10/model-validation-aspnet-core-100933316-large.jpg?auto=webp&quality=85,70″/ > IDG Figure 1: Model recognition in a minimal API in ASP.NET Core 6 using the FluentValidation library. You can likewise apply custom validators using the IValidatableObject user interface.
This user interface contains a technique named Validate, which you would need to implement yourself. To do so, you would develop a design class that executes this interface and the Validate approach. I’ll go over using IValidatableObject in
a future post here. Copyright © 2022 IDG Communications, Inc. Source