Last active
August 17, 2025 14:18
-
-
Save BashkaMen/18faee966b7d6f708edf771ea2f75c2f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| public interface IEndpoint | |
| { | |
| static abstract void MapEndpoints(IEndpointRouteBuilder app); | |
| } | |
| public static partial class EndpointExt | |
| { | |
| [GenerateServiceRegistrations(AssignableTo = typeof(IEndpoint), CustomHandler = nameof(MapEndpoint))] | |
| public static partial IEndpointRouteBuilder MapOwnlyEndpoints(this IEndpointRouteBuilder endpoints); | |
| private static void MapEndpoint<T>(IEndpointRouteBuilder endpoints) where T : IEndpoint | |
| { | |
| T.MapEndpoints(endpoints); | |
| } | |
| } | |
| public class StartTime : IEndpoint | |
| { | |
| private static readonly long StartupTime = Stopwatch.GetTimestamp(); | |
| public static void MapEndpoints(IEndpointRouteBuilder app) | |
| { | |
| app.MapGet("/startup-time", Handler); | |
| } | |
| public static Response Handler( | |
| [FromServices] AppDbContext dbContext, | |
| [FromHeader(Name = "X-Forwarded-For")] string? clientIp | |
| ) | |
| { | |
| return new(StartupTime); | |
| } | |
| public record Response( | |
| [property: JsonPropertyName("startup_time")] | |
| long StartupTime | |
| ); | |
| } | |
| public class ValidationFilter : IEndpointFilter | |
| { | |
| public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) | |
| { | |
| var items = context.Arguments | |
| .Select(arg => | |
| { | |
| var itemType = arg.GetType(); | |
| var validatorType = typeof(IValidator<>).MakeGenericType(itemType); | |
| var validator = context.HttpContext.RequestServices.GetService(validatorType); | |
| if (validator is null) return null; | |
| return new { Arg = arg, Validator = (IValidator)validator }; | |
| }) | |
| .Where(x => x is not null); | |
| foreach (var item in items) | |
| { | |
| var ctx = new ValidationContext<object>(item.Arg); | |
| var result = await item.Validator.ValidateAsync(ctx); | |
| if (!result.IsValid) | |
| { | |
| return Results.BadRequest(result.ToDictionary()); | |
| } | |
| } | |
| return await next.Invoke(context); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment