|
| 1 | +namespace TodoApi; |
| 2 | + |
| 3 | +using System.Reflection; |
| 4 | +using Microsoft.AspNetCore.Http.Metadata; |
| 5 | +using MiniValidation; |
| 6 | + |
| 7 | +public static class ValidationFilterExtensions |
| 8 | +{ |
| 9 | + public static TBuilder WithParameterValidation<TBuilder>( |
| 10 | + this TBuilder builder, |
| 11 | + params Type[] typesToValidate |
| 12 | + ) |
| 13 | + where TBuilder : IEndpointConventionBuilder |
| 14 | + { |
| 15 | + builder.Add(endpointBuilder => |
| 16 | + { |
| 17 | + var methodInfo = endpointBuilder.Metadata.OfType<MethodInfo>().FirstOrDefault(); |
| 18 | + |
| 19 | + if (methodInfo is null) |
| 20 | + { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + // Track the indices of validatable parameters |
| 25 | + List<int>? parameterIndexesToValidate = null; |
| 26 | + foreach ( |
| 27 | + var p in methodInfo |
| 28 | + .GetParameters() |
| 29 | + .Where(p => typesToValidate.Contains(p.ParameterType)) |
| 30 | + ) |
| 31 | + { |
| 32 | + parameterIndexesToValidate ??= []; |
| 33 | + parameterIndexesToValidate.Add(p.Position); |
| 34 | + } |
| 35 | + |
| 36 | + if (parameterIndexesToValidate is null) |
| 37 | + { |
| 38 | + // Nothing to validate so don't add the filter to this endpoint |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + // We can respond with problem details if there's a validation error |
| 43 | + endpointBuilder.Metadata.Add( |
| 44 | + new ProducesResponseTypeMetadata( |
| 45 | + typeof(HttpValidationProblemDetails), |
| 46 | + 400, |
| 47 | + "application/problem+json" |
| 48 | + ) |
| 49 | + ); |
| 50 | + |
| 51 | + AddValidation(endpointBuilder, parameterIndexesToValidate); |
| 52 | + }); |
| 53 | + |
| 54 | + return builder; |
| 55 | + } |
| 56 | + |
| 57 | + private static void AddValidation( |
| 58 | + EndpointBuilder endpointBuilder, |
| 59 | + List<int>? parameterIndexesToValidate |
| 60 | + ) => |
| 61 | + endpointBuilder.FilterFactories.Add( |
| 62 | + (context, next) => |
| 63 | + ctx => |
| 64 | + { |
| 65 | + foreach (var index in parameterIndexesToValidate!) |
| 66 | + { |
| 67 | + if ( |
| 68 | + ctx.Arguments[index] is { } arg |
| 69 | + && !MiniValidator.TryValidate(arg, out var errors) |
| 70 | + ) |
| 71 | + { |
| 72 | + return new ValueTask<object?>(Results.ValidationProblem(errors)); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return next(ctx); |
| 77 | + } |
| 78 | + ); |
| 79 | + |
| 80 | + // Equivalent to the .Produces call to add metadata to endpoints |
| 81 | + private sealed class ProducesResponseTypeMetadata(Type type, int statusCode, string contentType) |
| 82 | + : IProducesResponseTypeMetadata |
| 83 | + { |
| 84 | + public Type Type { get; } = type; |
| 85 | + public int StatusCode { get; } = statusCode; |
| 86 | + public IEnumerable<string> ContentTypes { get; } = [contentType]; |
| 87 | + } |
| 88 | +} |
0 commit comments