0
votes

I'm trying to set up fluent validation for .net core.

I've been following a guide which tells me: * Add the aspnetcore fluent validation package * Make your rules in a custom validator * Register it at startup.

I'm trying to get it working, and it only works when in my code I instantiate an instance of the validator and then validate. I want to validate it on the request coming through before it even gets there!

Why isn't this working?

My code so far:

[HttpPost]
        public async Task<IActionResult> PostAsync([FromBody]GraphQlQuery query)
        {
            try
            {
                using (PerformanceTimer.StartNew("Performing GraphQL query", str=> LogHelper.Info(str)))
                {
                    if (!ModelState.IsValid)
                    {
                        return null;
                    }

Startup.cs

services.AddMvc(opt => opt.Filters.Add(typeof(ValidatorActionFilter)))
                .AddFluentValidation(x => x.RegisterValidatorsFromAssemblyContaining<AccountValidator>())

Validator:

public class AccountValidator : AbstractValidator<Account>
    {
        public AccountValidator()
        {
            RuleFor(c => c.CreditLimit)
                .LessThan(0).WithMessage("Credit Limit can not be less than 0")
                .GreaterThan(100).WithMessage("Credit Limit can not be greater than 100");


    }
}

It works when I do this though:

var accountValidator = new AccountValidator();
                       x.Add(accountValidator.Validate(new Account { CreditLimit = 999}));

I've updated the object, so this should be getting hit. I added the CreditLimit as 101.

Why isn't this working in the pipeline when my api gets hit?

2

2 Answers

1
votes

The first change I would recommend you is to change .AddFluentValidation to

.AddFluentValidation(x => {x.RegisterValidatorsFromAssemblyContaining<Startup>();});

This causes all validators contained in your assembly to be loaded automatically.

Second thing which caused me the same problem was that Validators were not contained in the same projects. I had Validator classes in Core project instead of Api, where startup comes from.

0
votes

FluentValidation works validating the entry parameters of the Endpoint. In your case this should work if you want to validate the Account from the body. If you want to validate the Query you have to write a QueryValidator.

[HttpPost]
        public async Task<IActionResult> PostAsync([FromBody]Account account)
        {
            try
            {
                using (PerformanceTimer.StartNew("Performing GraphQL query", str=> LogHelper.Info(str)))
                {
                    if (!ModelState.IsValid)
                    {
                        return null;
                    }