Search code examples
asp.net-corefluentvalidation

asp.net core web api project how to with fluentvalidation auto-validation


I want to use fluentvalidation to automatically verify exceptions, but I can’t do this now. If I put the Validator in the same one project, it will work, but if I put it Validator in another library, it will not work。 The following project one

public class TestValidator : AbstractValidator<WeatherForecast>
{
    public TestValidator()
    {
        RuleFor(x => x.Summary).NotEmpty().WithMessage("Username or email are required");
    }

}

The following project two

I said that registration and verification are placed in different projects, which leads to abnormal verification.

services.AddMvc(options =>
    {
        options.Filters.Add(new ExceptionFilter());
    })
    .AddFluentValidation(options =>
    {
        options.RegisterValidatorsFromAssemblyContaining<Startup>();
    });

Solution

  • You need change your startup to :

     .AddFluentValidation(options =>
    {
        options.RegisterValidatorsFromAssemblyContaining<TestValidator>();
    });
    

    Test result:

    enter image description here