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

Deal Score0
Deal Score0


When working with functions in ASP.NET Core 6 you’ll typically wish to validate your fashions to make sure that the information 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 the way to use mannequin validation in minimal APIs.

To work with the code examples supplied on this article, it is best to have Visible Studio 2022 put in in your system. Should you don’t have already got a replica, you’ll be able to download Visual Studio 2022 here.

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

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

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

It will create a brand new ASP.NET Core 6 Internet API undertaking in Visible Studio 2022. We’ll use this undertaking 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 information within the mannequin conforms to the outlined guidelines. Allow us to perceive this with an instance. Assume you could have a mannequin class named Product, during which one of many fields is the Product Code.

Now suppose you could have outlined an attribute within the Product class whereby the Product Code property can not have a price 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 will have to put in writing your personal customized code to validate the fashions in your minimal API functions.

Set up the FluentValidation.AspNetCore NuGet bundle

On this article, we’ll use the FluentValidation validation library, which is offered 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 undertaking. To do that, choose the undertaking 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’ll be able to set up the bundle by way of the NuGet Bundle Supervisor console by coming into the command proven under.

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; }
}

It will 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 may create a customized validator by extending the summary class named AbstractValidator as proven within the code snippet given under.

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 an information retailer comparable 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 is not going to embrace the logic so as to add a product report 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 under.

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

Register the validator and repository lessons 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);
});

Word how the parameters validator, repository, and product have been handed. The ValidateAsync technique is known as to validate the product occasion.

Full mannequin validation instance

The whole supply code of the Program.cs file is given under to your reference.

utilizing FluentValidation;
var builder = WebApplication.CreateBuilder(args);
// Add providers 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 applying

Lastly, let’s execute the applying and invoke the HttpPost endpoint from Postman to see mannequin validation in motion. Determine 1 reveals the output upon validation of the mannequin. Word 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 can too apply customized validators utilizing the IValidatableObject interface. This interface incorporates a way named Validate, which you’d must 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 put up right here.

Copyright © 2022 IDG Communications, Inc.

We will be happy to hear your thoughts

Leave a reply

informatify.net
Logo
Enable registration in settings - general