Skip to content

luizhlelis/JSM.FluentValidation.AspNet.AsyncFilter

 
 

Repository files navigation

JSM.FluentValidation.AspNet.AsyncFilter

Quality Gate Status Coverage Nuget

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.

Get Started

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.

Custom Status Code

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);

Customization

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.

Contributing

See CONTRIBUTING.md.

About

ASP.NET filter that performs async validation using FluentValidation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 96.5%
  • Shell 3.5%