FluentValidation documentation states:
You should not use asynchronous rules when using automatic validation with ASP.NET as ASP.NET’s validation pipeline is not asynchronous. If you use asynchronous rules with ASP.NET’s automatic validation, they will always be run synchronously.
This library provides an ASP.NET filter that performs async Validation using FluentValidation.
To use the filter, first install the NuGet package:
dotnet add package JSM.FluentValidation.AspNet.AsyncFilter
Then, it's necessary to register the filter on the ConfigureServices
portion of the Startup.cs
.
services
.AddControllers
.AddModelValidationAsyncActionFilter();
The next step is to register the validators of the API:
services
.AddScoped<IValidator<MyClass>, MyClassValidator>>();
Or use automatic registration.
Currently, JSM.FluentValidation.AspNet.AsyncFilter
supports the following status codes:
- 400, Bad Request
- 403, Forbidden (
ErrorCode.Forbidden
) - 404, Not Found (
ErrorCode.NotFound
)
By default, every client error will return a 400 status code (Bad Request). If you want to customize the response, use FluentValidation's WithErrorCode():
RuleFor(user => user)
.Must(user => user.Id != "321")
.WithMessage("Insufficient rights to access this resource")
.WithErrorCode(ErrorCode.Forbidden);
If also possible to apply the filter only to controllers that contains the ApiControllerAttribute
.
...
.AddModelValidationAsyncActionFilter(options =>
{
options.OnlyApiController = true;
});
This way, other controllers requests without the attribute will be ignored.
See CONTRIBUTING.md.