Friday, October 14, 2022
HomeITUse mannequin validation in minimal APIs in ASP.NET Core 6

Use mannequin validation in minimal APIs in ASP.NET Core 6


When working with purposes in ASP.NET Core 6 you’ll typically wish to validate your fashions to make sure that the info they comprise conform to the pre-defined validation guidelines. Enter mannequin validation.

We’ve mentioned how we will get began with minimal APIs in an earlier article. This text discusses use mannequin validation in minimal APIs.

To work with the code examples supplied on this article, it’s best to have Visible Studio 2022 put in in your system. Should you don’t have already got a replica, you may obtain Visible Studio 2022 right here.

Create an ASP.NET Core minimal Internet API challenge in Visible Studio 2022

First off, let’s create an ASP.NET Core challenge in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API 6 challenge in Visible Studio 2022:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “ASP.NET Core Internet API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window, specify the title and site for the brand new challenge.
  6. Optionally test the “Place resolution and challenge in the identical listing” test field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Info” window proven subsequent, uncheck the checkbox that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Depart the “Authentication Kind” as “None” (default).
  9. Be sure that the test containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we gained’t be utilizing any of these options right here.
  10. Click on Create.

This may create a brand new ASP.NET Core 6 Internet API challenge in Visible Studio 2022. We’ll use this challenge to work with mannequin validation within the subsequent sections of this text.

What’s mannequin validation? Why is it wanted?

Mannequin validation is a method used to validate mannequin state, i.e., to find out if the info within the mannequin conforms to the outlined guidelines. Allow us to perceive this with an instance. Assume you will have a mannequin class named Product, during which one of many fields is the Product Code.

Now suppose you will have outlined an attribute within the Product class whereby the Product Code property can’t have a worth that’s longer than 5 characters. Should you create an occasion of this mannequin class and assign greater than 5 characters to the Product Code property, then mannequin validation for this object will fail.

There isn’t any built-in help for mannequin validation in minimal APIs (in contrast to in ASP.NET Core MVC and Razor Pages). Therefore, you have to to jot down your personal customized code to validate the fashions in your minimal API purposes.

Set up the FluentValidation.AspNetCore NuGet bundle

On this article, we’ll use the FluentValidation validation library, which is on the market as a NuGet bundle. FluentValidation makes use of a fluent API and lambda expressions to create information validation guidelines.

Now add the FluentValidation.AspNetCore NuGet bundle to your challenge. To do that, choose the challenge within the Answer Explorer window, then right-click and choose “Handle NuGet Packages.” Within the NuGet Bundle Supervisor window, seek for the FluentValidation.AspNetCore bundle and set up it.

Alternatively, you may set up the bundle through the NuGet Bundle Supervisor console by getting into the command proven beneath.

PM> Set up-Bundle FluentValidation.AspNetCore

Create the mannequin class

Create a brand new class named Product in a file with the identical title and a .cs extension, and enter the next code in there.

public class Product
{
    public int Id { get; set; }
    public string Code { get; set; }
    public int Amount { get; set; }
    public double Worth { get; set; }
}

This may function the mannequin class we’ll use for validation.

Create the ProductValidator class

Now suppose the Product class requires a validator, i.e., a category that may validate the properties of the Product class. You’ll be able to create a customized validator by extending the summary class named AbstractValidator as proven within the code snippet given beneath.

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

Create the IProductRepository interface

A repository is utilized in an software to persist information to a knowledge retailer equivalent to a database or a file system. On this instance, we’ll create a easy repository that has a way named AddProduct, however since we’re specializing in mannequin validation right here, we won’t embrace the logic so as to add a product document to the database.

Create an interface named IProductRepository and enter the next code.

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

Create the ProductRepository class

The ProductRepository class implements the IProductRepository interface as proven beneath.

public class ProductRepository : IProductRepository
{
    public void AddProduct(Product product)
    {
        //Write your code right here so as to add a product document to the database
    }
}

Register the validator and repository courses in Program.cs

Register the ProductValidator and ProductRepository varieties within the Program.cs file utilizing the next code.

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

Create a HttpPost endpoint in Program.cs

Now write the next code within the Program.cs file to create a HttpPost endpoint.

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

Observe how the parameters validator, repository, and product have been handed. The ValidateAsync technique is named to validate the product occasion.

Full mannequin validation instance

The entire supply code of the Program.cs file is given beneath on your reference.

utilizing FluentValidation;
var builder = WebApplication.CreateBuilder(args);
// Add companies to the container.
builder.Providers.AddScoped<IValidator<Product>, ProductValidator>();
builder.Providers.AddScoped<IProductRepository, ProductRepository>();
var app = builder.Construct();
// 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 Outcomes.ValidationProblem(validationResult.ToDictionary());
    }
    repository.AddProduct(product);
    return Outcomes.Created($"/{product.Id}", product);
});
app.Run();

Execute the appliance

Lastly, let’s execute the appliance and invoke the HttpPost endpoint from Postman to see mannequin validation in motion. Determine 1 exhibits the output upon validation of the mannequin. Observe the error messages within the response.

model validation aspnet core IDG

Determine 1: Mannequin validation in a minimal API in ASP.NET Core 6 utilizing the FluentValidation library.

You may also apply customized validators utilizing the IValidatableObject interface. This interface incorporates a way named Validate, which you’d have to implement your self. To take action, you’ll create a mannequin class that implements this interface and the Validate technique. I’ll focus on using IValidatableObject in a future submit right here.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments