Skip to content

Instantly share code, notes, and snippets.

@gordysc
Last active September 25, 2024 01:30
Show Gist options
  • Save gordysc/59a4e23fc8ea9fae686a4480385858ad to your computer and use it in GitHub Desktop.
Save gordysc/59a4e23fc8ea9fae686a4480385858ad to your computer and use it in GitHub Desktop.
C# Minimal API ValidationFilter w/ FluentValidations
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