The easiest way to validate web apis from .NET6 MinimalApis.
Inspired in an example of Nick Chapsa.
Thank's a lot Nick Chapsa !!!
- MinimalApis.Validators - Validator using DataAnnotation.
- MiimalApis.Validators.FluentValidation - Validator using package FluentValidation.
Only use the key WithValidator<> in your endpoint and finish:
app.MapPost("/customer",(Customer customer) =>
{
return Results.Created(nameof(customer), customer);
}).WithValidator<Customer>();
var app = WebApplication.Create(args);
app.MapPost("/customer",(Customer customer) =>
{
return Results.Created(nameof(customer), customer);
}).WithValidator<Customer>();
app.Run("http://localhost:5010");
public class Customer
{
[Required]
public string Name { get; set; } = "";
[Required]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; } = "";
}
More details in source example Example With DataAnnotation
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly);
var app = builder.Build();
app.MapPost("/customer",(Customer customer) =>
{
return Results.Created(nameof(customer),customer);
}).WithValidator<Customer>();
app.Run("http://localhost:5005");
public class Customer
{
public string Name { get; set; } = "";
public int Age { get; set; }
public string Email { get; set; } = "";
}
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(x => x.Name).NotEmpty();
RuleFor(x => x.Age).GreaterThan(0);
RuleFor(x => x.Email).EmailAddress();
}
}
More details in source example Example With FluentValidation
Special credit to Nick Chapsa to made it's possible.
Maintained by Junior Porfirio - follow me on twitter @juniorporfirio for updates.