Showing posts with label DotNet/dotnetCore. Show all posts
Showing posts with label DotNet/dotnetCore. Show all posts

FluentValidation in minimal APIs in ASP.NET Core 7.0

FluentValidation in minimal APIs in ASP.NET Core 7.0

 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.

FluentValidation in minimal APIs in ASP.NET Core 7.0

Now give the project name 'FluentValidationInAspCore' and click Next.

FluentValidation in minimal APIs in ASP.NET Core 7.0

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 click on the project solution.

FluentValidation in minimal APIs in ASP.NET Core 7.0

Once you click on Manage Nuget packages, a new window will appear. Search for "FluentValidation.AspNetCore" and install it.

FluentValidation in minimal APIs in ASP.NET Core 7.0

Now right-click on the project and create a Student Model class like below

namespace FluentValidationInAspCore {
    public class Student {
        public int Id {
            get;
            set;
        }
        public string ? Name {
            get;
            set;
        }
        public int Age {
            get;
            set;
        }
        public double Address {
            get;
            set;
        }
    }
}
C#

FluentValidation in minimal APIs in ASP.NET Core 7.0

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.

public class StudentValidator: AbstractValidator < Student > {
    public StudentValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(15);
        RuleFor(x => x.Age).NotNull().InclusiveBetween(5, 20);
        RuleFor(x => x.Address).NotNull().LessThanOrEqualTo(200);
    }
}
C#

FluentValidation in minimal APIs in ASP.NET Core 7.0

Now create an interface IstudentBuilder class and write the below code to add the student information.

public interface IstudentBuilder {
    public void AddStudent(Student student);
}
C#

FluentValidation in minimal APIs in ASP.NET Core 7.0

Now create a studentBuilder class and inherit it from the Istudentbuilder interface and implement the method.

public class StudentBuilder: IstudentBuilder {
    public void AddStudent(Student student) {
        // Write your logic to add data into the database
    }
}
C#

FluentValidation in minimal APIs in ASP.NET Core 7.0

Now we need to register our validator class and builder classes to Program.cs like below

using FluentValidation;
using FluentValidationInAspCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped < IValidator < Student > , StudentValidator > ();
builder.Services.AddScoped < IstudentBuilder, StudentBuilder > ();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
C#

FluentValidation in minimal APIs in ASP.NET Core 7.0

Create the HttpPost endpoint in the Program.cs

Write the below code to create the HTTP POST endpoint in minimal API.

app.MapPost("/student", async (IValidator < Student > validator, IstudentBuilder builder, Student student) => {
    var validationResult = await validator.ValidateAsync(student);
    if (!validationResult.IsValid) {
        return Results.ValidationProblem(validationResult.ToDictionary());
    }
    builder.AddStudent(student);
    return Results.Created($ "/{student.Id}", student);
});
C#

FluentValidation in minimal APIs in ASP.NET Core 7.0

Now run your application on swagger. Click on the Try it out button.

FluentValidation in minimal APIs in ASP.NET Core 7.0

Without giving any value, if you run it, you will see a validation error like below.

FluentValidation in minimal APIs in ASP.NET Core 7.0

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

----------------------------------------------------------- 


 Want to be an art expert, follow the below link Guide to Teaching Art eBook https://www.digistore24.com/redir/422234/TheDotNetOffice/CAMPAIGNKEY
--------------------------

Package validation in .Net

Package validation in .Net

 In this article, we are going to learn about package validation in .Net

package validation was introduced in .NET 6 SDK. It allows developers to ensure the packages we get from NuGet package managers and even verify whether the NuGet package manager is consistent.

Package validation helps us in following things to verify

  1. It allows the developer to validate that there are no breaking changes across all the versions of packages.
  2. Package Validation allows developers to validate that all our packages are consistent and well-formed.
  3. It will help developers catch any applicability holes.
  4. Validates that all packages have the same set of public APIs for different runtime-specific implementations. 

Setup package validation in Project

To set up the package validation for the application, we need to set up a property in csproj file like below. 

To set up this, we need to make the EnablePackageValidation property true

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <EnablePackageValidation>true</EnablePackageValidation>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.2" />
  </ItemGroup>
</Project>
JavaScript

How to validate the packages
 

1. Validating Compatible Frameworks

The Validating Compatible Frameworks validate that the code compiled against one framework can run against all the other frameworks in the multi-targeting packages. 

Package Validation will catch all the errors at the package installation time, for ex. 

Suppose we are writing a game code in which we do many string manipulation. We need to support both the .NET Framework and the .NET Core consumers. So we started with targeting .NET Standard 2.0, but later on, we realize we want to use spans in .NET 6.0 to avoid the unnecessary string allocations, So to do that, we now want the multi-target for .NET Standard 2.0 and .NET 6.0, below is the code for same.

#if Framework NET6_0_OR_GREATER
public void DoStringManipulation(ReadOnlySpan < char > val) {
    // use te spans to do the string operations.
}
#else
public void DoStringManipulation(string val) {
    // Do the string operations.
}
#endif
C#

Now if we install the package in the project (using DotNet package manager or cmd) it will give the below error

Package validation in .Net

So as shown in error, we should not exclude DoStringManipulation(string). Instead, we need to give another DoStringManipulation (ReadoOnlySpan<char>) method for .NET 6.0, so the code will be like below

#if NET6_0_OR_GREATER
public void DoStringManipulation(ReadOnlySpan < char > val) {
    // use te spans to do the string operations.
}
#endif
public void DoStringManipulation(string val) {
    // Do the string operations.
}
C#

2. Baseline version validator

 The Baseline version validator validates the packages library project against the previously released packages, basically the stable version. Package validation identifies any breaking change.

To use it, we need to add the PackageValidationBaselineVersion or PackageValidationBaselinePath in our project.

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <EnablePackageValidation>true</EnablePackageValidation>
    <PackageVersion>2.0.0</PackageVersion>
    <PackageValidationBaselineVersion>1.0.0</PackageValidationBaselineVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.2" />
  </ItemGroup>
</Project>
JavaScript

We can even use the PackageValidationBaselinePath property as well to identify the breaking changes

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <EnablePackageValidation>true</EnablePackageValidation>
    <PackageVersion>2.0.0</PackageVersion>
    <PackageValidationBaselinePath>PackagePath</PackageValidationBaselinePath> >
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.2" />
  </ItemGroup>
</Project>
JavaScript

3. Validation Against Diff Runtimes

The Compatible runtime validator validates run times assemblies that are compatible with the compile time assemblies.

----------------------------------------------------------- 

 Want to be an art expert, follow the below link Guide to Teaching Art eBook https://www.digistore24.com/redir/422234/TheDotNetOffice/CAMPAIGNKEY

------------------