| | | 1 | | using System.ComponentModel.DataAnnotations; |
| | | 2 | | using System.Reflection; |
| | | 3 | | |
| | | 4 | | namespace ClutterStock.Api.Filters; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Endpoint filter that runs <see cref="System.ComponentModel.DataAnnotations" /> validation |
| | | 8 | | /// on every endpoint argument. Returns an RFC 7807 <c>ValidationProblemDetails</c> response |
| | | 9 | | /// when validation fails. Applied group-wide by the endpoint source generator. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <remarks> |
| | | 12 | | /// This filter is the project's validation strategy because the .NET 10 minimal-API |
| | | 13 | | /// <c>AddValidation()</c> source generator can't statically resolve our endpoints — they |
| | | 14 | | /// are mapped via <c>MapPost(route, EndpointType.Handler)</c> where <c>Handler</c> is a |
| | | 15 | | /// <see cref="Delegate" />-typed property. The generator skips such call sites and emits |
| | | 16 | | /// no validatable-type info, leaving validation as a no-op. |
| | | 17 | | /// </remarks> |
| | | 18 | | internal sealed class DataAnnotationsValidationFilter : IEndpointFilter |
| | | 19 | | { |
| | | 20 | | public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) |
| | | 21 | | { |
| | 42 | 22 | | var parameters = context.HttpContext.GetEndpoint() |
| | 42 | 23 | | ?.Metadata |
| | 42 | 24 | | .GetMetadata<MethodInfo>() |
| | 42 | 25 | | ?.GetParameters(); |
| | | 26 | | |
| | 42 | 27 | | Dictionary<string, List<string>>? errors = null; |
| | | 28 | | |
| | 342 | 29 | | for (var i = 0; i < context.Arguments.Count; i++) |
| | | 30 | | { |
| | 129 | 31 | | var argument = context.Arguments[i]; |
| | 129 | 32 | | if (argument is null) |
| | | 33 | | continue; |
| | | 34 | | |
| | 129 | 35 | | var parameter = parameters is not null && i < parameters.Length ? parameters[i] : null; |
| | 129 | 36 | | ValidateArgument(argument, parameter, ref errors); |
| | | 37 | | } |
| | | 38 | | |
| | 42 | 39 | | if (errors is not null) |
| | | 40 | | { |
| | 9 | 41 | | var formatted = errors.ToDictionary(static kv => kv.Key, static kv => kv.Value.ToArray()); |
| | 9 | 42 | | return Results.ValidationProblem(formatted); |
| | | 43 | | } |
| | | 44 | | |
| | 33 | 45 | | return await next(context); |
| | 42 | 46 | | } |
| | | 47 | | |
| | | 48 | | private static void ValidateArgument(object argument, ParameterInfo? parameter, ref Dictionary<string, List<string>> |
| | | 49 | | { |
| | 129 | 50 | | if (IsSimpleType(argument.GetType())) |
| | | 51 | | { |
| | 18 | 52 | | if (parameter is null) |
| | 0 | 53 | | return; |
| | | 54 | | |
| | 18 | 55 | | var attributes = parameter.GetCustomAttributes<ValidationAttribute>(inherit: true).ToArray(); |
| | 18 | 56 | | if (attributes.Length == 0) |
| | 0 | 57 | | return; |
| | | 58 | | |
| | 18 | 59 | | var results = new List<ValidationResult>(); |
| | 18 | 60 | | var ctx = new ValidationContext(argument) |
| | 18 | 61 | | { |
| | 18 | 62 | | MemberName = parameter.Name |
| | 18 | 63 | | }; |
| | 18 | 64 | | if (Validator.TryValidateValue(argument, ctx, results, attributes)) |
| | 18 | 65 | | return; |
| | | 66 | | |
| | 0 | 67 | | AddResults(results, parameter.Name ?? string.Empty, ref errors); |
| | 0 | 68 | | return; |
| | | 69 | | } |
| | | 70 | | |
| | 111 | 71 | | var objectResults = new List<ValidationResult>(); |
| | 111 | 72 | | var objectContext = new ValidationContext(argument); |
| | 111 | 73 | | if (Validator.TryValidateObject(argument, objectContext, objectResults, validateAllProperties: true)) |
| | 102 | 74 | | return; |
| | | 75 | | |
| | 9 | 76 | | AddResults(objectResults, fallbackKey: argument.GetType().Name, ref errors); |
| | 9 | 77 | | } |
| | | 78 | | |
| | | 79 | | private static void AddResults(IEnumerable<ValidationResult> results, string fallbackKey, ref Dictionary<string, Lis |
| | | 80 | | { |
| | 38 | 81 | | foreach (var result in results) |
| | | 82 | | { |
| | 10 | 83 | | var message = result.ErrorMessage ?? "Invalid value"; |
| | 10 | 84 | | var members = result.MemberNames.Any() ? result.MemberNames : [fallbackKey]; |
| | 40 | 85 | | foreach (var member in members) |
| | | 86 | | { |
| | 10 | 87 | | errors ??= new Dictionary<string, List<string>>(); |
| | 10 | 88 | | if (!errors.TryGetValue(member, out var list)) |
| | 10 | 89 | | errors[member] = list = []; |
| | 10 | 90 | | list.Add(message); |
| | | 91 | | } |
| | | 92 | | } |
| | 9 | 93 | | } |
| | | 94 | | |
| | | 95 | | private static bool IsSimpleType(Type type) |
| | | 96 | | { |
| | 129 | 97 | | var underlying = Nullable.GetUnderlyingType(type) ?? type; |
| | 129 | 98 | | return underlying.IsPrimitive |
| | 129 | 99 | | || underlying.IsEnum |
| | 129 | 100 | | || underlying == typeof(string) |
| | 129 | 101 | | || underlying == typeof(decimal) |
| | 129 | 102 | | || underlying == typeof(DateTime) |
| | 129 | 103 | | || underlying == typeof(DateTimeOffset) |
| | 129 | 104 | | || underlying == typeof(TimeSpan) |
| | 129 | 105 | | || underlying == typeof(Guid); |
| | | 106 | | } |
| | | 107 | | } |