|
| 1 | +using FluentValidation; |
| 2 | +using Initium.Infrastructure; |
| 3 | +using Initium.Response; |
| 4 | +using Microsoft.AspNetCore.Http; |
| 5 | +using Microsoft.AspNetCore.Mvc.Filters; |
| 6 | + |
| 7 | +namespace Initium.Filters; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// A filter that performs implicit validation on actions using requests derived from <see cref="BaseRequestWithValidator{T}"/>. |
| 11 | +/// </summary> |
| 12 | +internal class ImplicitValidationFilter : IActionFilter |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Called before the action executes, to validate the action arguments. |
| 16 | + /// </summary> |
| 17 | + /// <param name="context">The context for the action execution.</param> |
| 18 | + public void OnActionExecuting(ActionExecutingContext context) |
| 19 | + { |
| 20 | + var argument = context.ActionArguments.Values.FirstOrDefault(); |
| 21 | + if (argument == null) return; |
| 22 | + |
| 23 | + var argumentType = argument.GetType(); |
| 24 | + var baseType = argumentType.BaseType; |
| 25 | + |
| 26 | + if (baseType is not { IsGenericType: true } || baseType.GetGenericTypeDefinition() != typeof(BaseRequestWithValidator<>)) return; |
| 27 | + |
| 28 | + var validatorType = baseType.GetGenericArguments().FirstOrDefault(); |
| 29 | + if (validatorType == null || Activator.CreateInstance(validatorType) is not IValidator validator) return; |
| 30 | + |
| 31 | + var validationContext = new ValidationContext<object>(argument); |
| 32 | + var validationResult = validator.Validate(validationContext); |
| 33 | + |
| 34 | + if (validationResult.IsValid) return; |
| 35 | + |
| 36 | + context.Result = ApiResponseBuilder |
| 37 | + .CreateFromContext(context.HttpContext) |
| 38 | + .WithMessage("One or more validation errors occurred.") |
| 39 | + .WithStatusCode(StatusCodes.Status400BadRequest) |
| 40 | + .WithErrors(validationResult.Errors) |
| 41 | + .BuildAsJsonResult(); |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Called after the action executes. No operation is performed in this implementation. |
| 46 | + /// </summary> |
| 47 | + /// <param name="context">The context for the executed action.</param> |
| 48 | + public void OnActionExecuted(ActionExecutedContext context) { } |
| 49 | +} |
0 commit comments