Fluent validator with minimal api endpoint never gets executed

215 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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();
 
// ...
0
On

Following the Author's blog, Make sure to add this to your Program.cs.

builder.Services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton);

I think this was mistakenly missed out in the README.md of this package.