Listen to this Post
URL: FluentValidation Global Validation Middleware
You Should Know:
FluentValidation is a powerful library for .NET that simplifies the process of input validation. It allows you to create complex validation rules with a clean and maintainable API. Below are some practical examples and commands to get you started with FluentValidation.
Basic Validation Rules
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Name).NotEmpty().WithMessage("Name is required.");
RuleFor(customer => customer.Email).EmailAddress().WithMessage("A valid email is required.");
RuleFor(customer => customer.Age).InclusiveBetween(18, 65).WithMessage("Age must be between 18 and 65.");
}
}
Asynchronous Validation
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Email)
.MustAsync(async (email, cancellationToken) => await IsUniqueEmailAsync(email))
.WithMessage("Email must be unique.");
}
private async Task<bool> IsUniqueEmailAsync(string email)
{
// Simulate an asynchronous check, e.g., against a database
await Task.Delay(100);
return email != "[email protected]";
}
}
Dependency Injection
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IValidator<Customer>, CustomerValidator>();
}
}
Global Validation Middleware
public class ValidationMiddleware
{
private readonly RequestDelegate _next;
public ValidationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var validator = context.RequestServices.GetService<IValidator<Customer>>();
var customer = await context.Request.ReadFromJsonAsync<Customer>();
var validationResult = await validator.ValidateAsync(customer);
if (!validationResult.IsValid)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(validationResult.Errors);
return;
}
await _next(context);
}
}
Linux Commands for .NET Development
<h1>Install .NET SDK on Ubuntu</h1> wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb sudo dpkg -i packages-microsoft-prod.deb sudo apt-get update sudo apt-get install -y dotnet-sdk-6.0 <h1>Create a new .NET project</h1> dotnet new webapi -n MyApi <h1>Run the application</h1> dotnet run --project MyApi
Windows Commands for .NET Development
[cmd]
:: Install .NET SDK on Windows
winget install Microsoft.DotNet.SDK.6
:: Create a new .NET project
dotnet new webapi -n MyApi
:: Run the application
dotnet run –project MyApi
[/cmd]
What Undercode Say:
FluentValidation is an essential tool for any .NET developer looking to implement robust input validation. By leveraging its simple API, you can ensure that your application handles user input securely and efficiently. The examples provided above demonstrate how to set up basic and asynchronous validation rules, integrate with dependency injection, and create global validation middleware. Additionally, the Linux and Windows commands will help you get started with .NET development on different platforms. For more advanced scenarios, consider exploring the official FluentValidation documentation and community resources.
Additional Resources:
References:
Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



