I'm trying to implement fluent validation extension on minimal api endpoint project
but I cannot manage to make it work
the project is .net 7 version with
<PackageReference Include="O9d.AspNet.FluentValidation" Version="0.1.1" />
<PackageReference Include="FluentValidation.AspNetCore" Version="11.2.2" />
Following documentation I try with following
var test = app.MapGroup("/")
.WithValidationFilter();
test.MapPost("/test-model", ([Validate][FromBody] TestModel model ) => "Hello World!");
app.Run();
public class TestModel
{
public long Id { get; set; }
public class TestModelValidator : AbstractValidator<TestModel>
{
public TestModelValidator()
{
RuleFor(x => x.Id).GreaterThan(0);
}
}
}
whatever I put in the body request it never get executed in the validator. Am I missing something here?
The docs are missing one step - you need to register validators. For example using the ability to register all from assembly (see FluentValidation integration with ASP.NET Core docs):
var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
var app = builder.Build();
// ...