Breaking

Thursday, October 20, 2022

Utilize model approval in negligible APIs in ASP.NET Code 6

Utilize model approval in negligible APIs in ASP.NET Code 6

Utilize model approval in negligible APIs in ASP.NET Code 6


Exploit FluentValidation to approve your model classes while working with negligible APIs in ASP.NET Code 6.

While working with applications in ASP.NET Code 6 you will frequently need to approve your models to guarantee that the information they contain adjusts to the pre-characterized approval rules. Enter model approval.

We've examined how we can begin with negligible APIs in a prior article. This article talks about how to involve model approval in negligible APIs.

To work with the code models given in this article, you ought to have Visual Studio 2022 introduced in your framework. On the off chance that you don't as of now have a duplicate, you can download Visual Studio 2022 here.

Make an ASP.NET Code negligible Web Programming interface project in Visual Studio 2022

Most importantly, we should make an ASP.NET Code task in Visual Studio 2022. Following these means will make another ASP.NET Code Web Programming interface 6 undertaking in Visual Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create a new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, uncheck the checkbox that says “Use controllers…” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here.
  10. Click Create.

This will make another ASP.NET Code 6 Web Programming interface project in Visual Studio 2022. We'll involve this venture to work with model approval in the resulting areas of this article.

What is model approval? For what reason is it required?

Model approval is a procedure used to approve code state, i.e., to decide whether the information in the model adjusts to the characterized rules. Allow us to figure out this with a model. Expect you have a model class named Item, in which one of the fields is the Item Code.

Presently guess you have characterized a trait in the Item class by which the Item Code property can't have a worth that is longer than five characters. In the event that you make a case of this model class and allot in excess of five characters to the Item Code property, then, at that point, model approval for this article will fall flat.

There is no underlying help for model approval in negligible APIs (not at all like in ASP.NET code MVC and Razor Pages). Subsequently, you should compose your own custom code to approve the models in your negligible Programming interface applications.

Introduce the FluentValidation.AspNetCore NuGet bundle

In this article, we'll utilize the FluentValidation approval library, which is accessible as a NuGet bundle. FluentValidation utilizes a familiar Programming interface and lambda articulations to make information approval rules.

Presently add the FluentValidation.AspNetCore NuGet bundle to your task. To do this, select the venture in the Arrangement Pilgrim window, then right-click and select "Oversee NuGet Bundles." In the NuGet Bundle Administrator window, look for FluentValidation.AspNetCore bundles and introduce it.

On the other hand, you can introduce the bundle through the NuGet Bundle Administrator console by entering the order displayed underneath.
PM> Install-Package FluentValidation.AspNetCore

Make the model class

Make another class named Item in a record with a similar name and a .cs expansion, and enter the accompanying code in there.

public class Product
{
    public int Id { get; set; }
    public string Code { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}
This will act as the model class we will use for approval.

Make the ProductValidator class

Presently guess the Item class requires a validator, i.e., a class that will approve the properties of the Item class. You can make a custom validator by expanding the theoretical class named AbstractValidator as displayed in the code bit given beneath.

public class ProductValidator : AbstractValidator<Product>
{
    public ProductValidator()
    {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Code).Length(5);
        RuleFor(x => x.Quantity).NotNull();
        RuleFor(x => x.Price).InclusiveBetween(50.00, 250.00);
    }
}


Make the IProductRepository interface

A vault is utilized in an application to persevere information to an information store like a data set or a document framework. In this model, we will make a basic store that has a technique named AddProduct, yet since we're zeroing in on model approval here, we wo exclude the rationale to add an item record to the data set.

Make a connection point named IProductRepository and enter the accompanying code.

public interface IProductRepository
{
    public void AddProduct(Product product);
}

Make the ProductRepository class

The ProductRepository class carries out the IProductRepository interface as displayed underneath.

public class ProductRepository : IProductRepository
{
    public void AddProduct(Product product)
    {
        //Write your code here to add a product record to the database
    }
}
Register the validator and store classes in Program.cs

Register the ProductValidator and ProductRepository types in the Program.cs document utilizing the accompanying code.

builder.Services.AddScoped<IValidator<Product>, ProductValidator>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();

Make a HttpPost endpoint in Program.cs

Presently compose the accompanying code in the Program.cs record to make a HttpPost endpoint.

app.MapPost("/product", async (IValidator<Product> validator, IProductRepository repository, Product product) =>
{
    var validationResult = await validator.ValidateAsync(product);
    if (!validationResult.IsValid)
    {
        return Results.ValidationProblem(validationResult.ToDictionary());
    }
    repository.AddProduct(product);
    return Results.Created($"/{product.Id}", product);
});

Note how the boundaries validator, store, and item have been passed. The ValidateAsync strategy is called to approve the item occurrence.

Complete model approval model

The total source code of the Program.cs record is given underneath for your reference.

using FluentValidation;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped<IValidator<Product>, ProductValidator>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapPost("/product", async (IValidator<Product> validator, IProductRepository repository, Product product) =>
{
    var validationResult = await validator.ValidateAsync(product);
    if (!validationResult.IsValid)
    {
        return Results.ValidationProblem(validationResult.ToDictionary());
    }
    repository.AddProduct(product);
    return Results.Created($"/{product.Id}", product);
});
app.Run();

Execute the application

In conclusion, how about we execute the application and summon the HttpPost endpoint from Mailman to see model approval in real life. Figure 1 shows the result upon approval of the model. Note the mistake messages in the reaction.

Utilize model approval in negligible APIs in ASP.NET Code 6

Figure 1: Model approval in a negligible Programming interface in ASP.NET code 6 utilizing the FluentValidation library.

You can likewise apply custom validators utilizing the IValidatableObject interface. This connection point contains a technique named Approve, which you would have to carry out yourself. To do as such, you would make a model class that executes this connection point and the Approve technique. I'll examine the utilization of IValidatableObject in a future post here.


No comments:

Post a Comment