In ASP.NET Core with FluentValidation 12, why must a validator with a MustAsync rule use ValidateAsync, and why is automatic MVC validation discouraged?
answer
- async rules need an async caller
- AsyncValidatorInvokedSynchronouslyException
- MVC's validation pipeline is synchronous
- MVC only, no Minimal APIs
- inject and call it yourself
basics
~10 sCalling Validate on a validator with async rules throws AsyncValidatorInvokedSynchronouslyException, so it must be awaited with ValidateAsync. MVC's validation pipeline is synchronous and MVC-only, so FluentValidation's docs advise calling validators explicitly instead of auto-validation.
solid answer
~50 sA rule such as `RuleFor(x => x.NationalId).MustAsync((id, ct) => bureau.HasFileAsync(id, ct))` can only run when the validator is invoked asynchronously. If code calls `validator.Validate(application)`, FluentValidation throws `AsyncValidatorInvokedSynchronouslyException`, an `InvalidOperationException` whose message says to call `ValidateAsync` rather than `Validate`. That is the root problem with automatic validation through the `FluentValidation.AspNetCore` package: it plugs into MVC's model validation, which runs synchronously, so a validator with async rules fails there with a message that the ASP.NET validation pipeline cannot invoke asynchronous rules. The FluentValidation docs list two more drawbacks: it works only for MVC controllers and Razor Pages, not Minimal APIs or Blazor, and its hidden behaviour is hard to debug. They no longer recommend it for new projects. The recommended pattern is to inject `IValidator<T>` and `await ValidateAsync(model, cancellationToken)` in the handler, or in a filter you control.
go deeper
Remember to await ValidateAsync whenever a validator has async rules such as MustAsync, instead of calling Validate.
Explain AsyncValidatorInvokedSynchronouslyException, why MVC's synchronous pipeline cannot host async rules, and the MVC-only limitation.
Replace auto-validation with explicit or filter-based ValidateAsync calls, pass cancellation tokens, and separate outages from validation failures.
Plan a migration off FluentValidation.AspNetCore auto-validation across services, weighing explicit calls, filters and third-party packages.
## Async rules need an async call FluentValidation rules can be synchronous (`NotEmpty`, `GreaterThan`, `Must`) or asynchronous (`MustAsync`, `CustomAsync`, `WhenAsync`). A lending API typically has at least one async rule, because checking an applicant against a credit bureau is an HTTP call: ```csharp public class LoanApplicationValidator : AbstractValidator<LoanApplication> { public LoanApplicationValidator(ICreditBureauClient bureau) { RuleFor(x => x.Amount).InclusiveBetween(1_000m, 250_000m); RuleFor(x => x.NationalId) .MustAsync((nationalId, ct) => bureau.HasFileAsync(nationalId, ct)) .WithMessage("No credit file found for this applicant."); } } ``` The validator has two entry points: | Call | Async rules | Outcome | |---|---|---| | `Validate(application)` | cannot run | throws `AsyncValidatorInvokedSynchronouslyException` | | `await ValidateAsync(application, ct)` | run and are awaited | returns a `ValidationResult` | `AsyncValidatorInvokedSynchronouslyException` derives from `InvalidOperationException`. Its message for a direct call is: the validator "contains asynchronous rules but was invoked synchronously. Please call ValidateAsync rather than Validate." Wrapping `ValidateAsync(...).Result` to dodge it blocks a thread-pool thread for the duration of the bureau call, which is exactly what async code exists to avoid. ## Why automatic MVC validation hits a wall The separate `FluentValidation.AspNetCore` package offered **automatic validation**: it registered FluentValidation as a model validator inside MVC, so validators ran during model binding and filled `ModelState` before the action, like DataAnnotations. Its constraints, as FluentValidation's own docs list them: 1. **The ASP.NET validation pipeline is not asynchronous.** MVC calls validators synchronously, so a validator with async rules cannot run. FluentValidation throws the same exception type with a message that the validator "can't be used with ASP.NET automatic validation as it contains asynchronous rules". 2. **It is MVC-only.** It works for controllers and Razor Pages, not for Minimal APIs or Blazor. 3. **It is harder to debug.** Validators run out of sight, before the action, so failures and their timing are less obvious. The docs conclude: "We no longer recommend using this approach for new projects but it is still available for legacy implementations." FluentValidation 12's upgrade notes describe 12 as a clean-up release with no new features, so nothing in 12 changes that advice. ## The recommended shape - **Inject `IValidator<T>`** into the endpoint, controller or service. - **Await `ValidateAsync`**, passing the request's `CancellationToken` so an abandoned request stops the bureau call. - **Map the result**: `ToDictionary()` into a validation problem for APIs, or copy into `ModelState` for views. - **Need it automatic?** Write a small endpoint filter or MVC action filter that resolves `IValidator<T>`, awaits it and short-circuits; or use a third-party package the docs mention (for example SharpGrip's auto-validation). Both stay asynchronous. ## Practical notes for the async rule - Keep remote checks last and cheap: run local rules first so an obviously invalid amount does not trigger an HTTP call. Rule ordering and cascade settings are rule-writing topics. - Remember the validator's dependencies: an `ICreditBureauClient` that is a typed `HttpClient` is transient; a scoped validator holding it is fine, a singleton is not. - An exception from the bureau call surfaces from `ValidateAsync`; decide whether that is a 503-style failure or a validation error, rather than letting it masquerade as invalid input. ## What interviewers listen for - The exception name and why it is thrown. - That MVC's synchronous validation pipeline is the reason async rules and auto-validation do not mix. - The other two drawbacks: MVC-only and opaque. - A clean replacement: injected `IValidator<T>` with `ValidateAsync`, optionally inside a filter.
- Why is validator.ValidateAsync(model).Result not an acceptable workaround in a request handler?`.Result` blocks the current thread until the bureau call completes, tying up a thread-pool thread per request. Under load that leads to thread-pool starvation and timeouts. Making the handler `async` and awaiting `ValidateAsync` releases the thread while the HTTP call is in flight.
- What should happen when the credit-bureau call itself fails inside MustAsync?The exception propagates out of `ValidateAsync`; it is not a validation failure. Let it reach the exception handling pipeline (or catch and map it) so the client gets a server-side error such as 503, instead of a 400 that blames the applicant's input. Validation errors should describe the request, not an outage.
- Validate runs MustAsync rules synchronously by blocking on them internally.
- FluentValidation.AspNetCore auto-validation works for Minimal APIs too.
- The auto-validation package was removed because FluentValidation 12 dropped async support.
- Calling ValidateAsync(...).Result is a safe fix for AsyncValidatorInvokedSynchronouslyException.
- A failing credit-bureau call should be reported as a 400 validation error.