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

.NET 7:如何为特定端点(login、refresh)禁用中间件?

为特定端点禁用中间件的实现方案

当然可以实现,不用硬编码请求路径,通过自定义特性标记方法的方式就能搞定,具体步骤如下:

  • 第一步:自定义跳过中间件的特性
    创建一个仅标记在方法上的特性,用来标识需要跳过目标中间件的接口方法:
[AttributeUsage(AttributeTargets.Method)]
public class SkipSomeMiddlewareAttribute : Attribute
{
}
  • 第二步:在目标接口方法上标记特性
    给login和refresh方法加上这个特性:
[SkipSomeMiddleware]
public IActionResult Login()
{
    // 登录业务逻辑
}

[SkipSomeMiddleware]
public IActionResult Refresh()
{
    // 令牌刷新业务逻辑
}
  • 第三步:修改中间件逻辑,检查特性
    在中间件的InvokeAsync方法里,通过HttpContext获取当前端点的元数据,判断是否存在跳过特性,存在则直接执行下一个中间件,不执行当前中间件的逻辑:
public class SomeMiddleware
{
    private readonly RequestDelegate _next;
    private readonly SomeArgs _someArgs;

    public SomeMiddleware(RequestDelegate next, SomeArgs someArgs)
    {
        _next = next;
        _someArgs = someArgs;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var endpoint = context.GetEndpoint();
        if (endpoint != null && endpoint.Metadata.GetMetadata<SkipSomeMiddlewareAttribute>() != null)
        {
            // 跳过当前中间件,直接走下一个
            await _next(context);
            return;
        }

        // 这里写中间件原本要执行的逻辑
        // ...

        // 执行后续中间件
        await _next(context);
    }
}

注意事项

这个方案依赖ASP.NET Core的端点路由(Endpoint Routing),确保你的Program.cs里已经配置了app.UseRouting()和app.UseEndpoints(...),否则无法获取到端点元数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:15:04