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?