You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Minimal API的IEndpointFilter中获取路由模板的实现方法

在Minimal API的自定义EndpointFilter中获取路由模板

要在自定义的MyFilter中获取定义的路由模板/get/{productId:guid},可以通过EndpointFilterInvocationContext的Endpoint属性获取当前匹配的路由端点信息,具体实现如下:

完整代码示例

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// 注册带自定义Filter的路由
app.MapGet("/get/{productId:guid}", (Guid productId) => Results.Ok($"Product ID: {productId}"))
   .AddEndpointFilter<MyFilter>();

app.Run();

public class MyFilter : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        // 获取当前路由模板
        if (context.Endpoint is RouteEndpoint routeEndpoint)
        {
            string routeTemplate = routeEndpoint.RoutePattern.ToString();
            // 可根据需求使用路由模板,如打印日志、参数校验等
            Console.WriteLine($"当前路由模板:{routeTemplate}");
        }
        
        return await next.Invoke(context);
    }
}

关键说明

  • context.Endpoint对应当前被匹配的端点实例,将其转换为RouteEndpoint类型(Minimal API的路由端点均为此类型)。
  • RouteEndpoint.RoutePattern属性存储了路由定义时的模板信息,调用ToString()即可直接得到/get/{productId:guid}格式的字符串。

内容的提问来源于stack exchange,提问作者Kazmir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:55:42