Last active
September 25, 2024 01:30
-
-
Save gordysc/59a4e23fc8ea9fae686a4480385858ad to your computer and use it in GitHub Desktop.
C# Minimal API ValidationFilter w/ FluentValidations
This file contains 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 FluentValidation; | |
public sealed class ValidationFilter<T> : IEndpointFilter | |
where T : class | |
{ | |
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) | |
{ | |
if (context.Arguments.FirstOrDefault(x => x?.GetType() == typeof(T)) is not { } argument) | |
return Results.Problem($"Missing argument type. Expected to validate {typeof(T).Name}."); | |
var validationType = typeof(ValidationContext<>).MakeGenericType(typeof(T)); | |
var validationContext = Activator.CreateInstance(validationType, argument) as IValidationContext; | |
var validator = context.HttpContext.RequestServices.GetRequiredService<IValidator<T>>(); | |
if (await validator.ValidateAsync(validationContext) is { IsValid: false } validation) | |
return Results.ValidationProblem(validation.ToDictionary()); | |
return await next(context); | |
} | |
} | |
public static class ValidationFilterExtensions | |
{ | |
public static RouteHandlerBuilder AddValidationFilter<T>(this RouteHandlerBuilder builder) | |
where T : class | |
{ | |
return builder.AddEndpointFilter<ValidationFilter<T>>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment