Created
December 9, 2022 05:44
-
-
Save wahidustoz/f9f838b06a6a1eb72e106a6293a80c87 to your computer and use it in GitHub Desktop.
Adds async auto validation to FluentValidation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading.Tasks; | |
| using FluentValidation; | |
| using FluentValidation.AspNetCore; | |
| using Microsoft.AspNetCore.Mvc.Filters; | |
| using Microsoft.AspNetCore.Mvc.ModelBinding; | |
| namespace Actions | |
| { | |
| public class AsyncAutoValidation : IAsyncActionFilter | |
| { | |
| public static int OrderLowerThanModelStateInvalidFilter => -2001; | |
| private readonly IServiceProvider serviceProvider; | |
| public AsyncAutoValidation(IServiceProvider serviceProvider) | |
| { | |
| this.serviceProvider = serviceProvider; | |
| } | |
| public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) | |
| { | |
| foreach (var parameter in context.ActionDescriptor.Parameters) | |
| { | |
| if ((parameter.BindingInfo.BindingSource == BindingSource.Body | |
| || parameter.BindingInfo.BindingSource == BindingSource.Query | |
| && parameter.ParameterType.IsClass) | |
| && serviceProvider.GetService(typeof(IValidator<>).MakeGenericType(parameter.ParameterType)) is IValidator validator) | |
| { | |
| var subject = context.ActionArguments[parameter.Name]; | |
| var result = await validator.ValidateAsync(new ValidationContext<object>(subject), context.HttpContext.RequestAborted); | |
| if (!result.IsValid) | |
| { | |
| result.AddToModelState(context.ModelState, null); | |
| } | |
| } | |
| } | |
| await next(); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| builder.Services.AddControllers().AddFluentValidationAsyncAutoValidation(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.Extensions.DependencyInjection; | |
| namespace Extensions | |
| { | |
| public static class ServiceCollectionExtensions | |
| { | |
| public static IMvcBuilder AddFluentValidationAsyncAutoValidation(this IMvcBuilder builder) | |
| { | |
| return builder.AddMvcOptions(o => | |
| { | |
| o.Filters.Add<AsyncAutoValidation>(AsyncAutoValidation.OrderLowerThanModelStateInvalidFilter); | |
| }); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment