asp.net.nethashidsfast-endpoints

How to use IRouteConstraint in FastEndpoints


Anyone know how to use IRouteConstraint in FastEndpoints? I have a existing class implemented IRouteConstraint and want to reuse it when I migrate to FastEndpoints? (I use it to parse hashids)


Solution

  • you can register custom route constraints the same way you would with minimal apis:

    var bld = WebApplication.CreateBuilder(args);
    bld.Services
       .Configure<RouteOptions>(c => c.ConstraintMap.Add("hasXYZ", typeof(MyConstraint)))
       .SwaggerDocument()
       .AddFastEndpoints();
    
    var app = bld.Build();
    app.UseFastEndpoints()
       .UseSwaggerGen();
    app.Run();
    
    sealed class MyConstraint : IRouteConstraint
    {
        public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (!values.TryGetValue(routeKey, out var routeValue))
                return false;
    
            var routeValueString = Convert.ToString(routeValue, CultureInfo.InvariantCulture);
    
            return routeValueString is not null && routeValueString.StartsWith("xyz");
        }
    }
    
    sealed class MyEndpoint : EndpointWithoutRequest
    {
        public override void Configure()
        {
            Get("test/{id:hasXYZ}");
            AllowAnonymous();
        }
    
        public override async Task HandleAsync(CancellationToken c)
        {
            await SendAsync(Route<string>("id"));
        }
    }