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

ASP.NET Core 8 Web API:如何让中间件仅在带[Authorize]的控制器执行

解决方案

1. 调整中间件逻辑

通过获取请求对应的Endpoint元数据,判断目标控制器或Action是否带有[Authorize]特性,仅在满足条件时执行中间件自定义逻辑:

public class CustomRequestMiddleware
{
    private readonly RequestDelegate _next;

    public CustomRequestMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
        bool needRunMiddleware = false;

        if (endpoint != null)
        {
            // 检查Endpoint元数据中是否包含Authorize特性(控制器或Action级别都生效)
            needRunMiddleware = endpoint.Metadata.Any(m => m is AuthorizeAttribute);
            
            // 可选:如果需要排除带[AllowAnonymous]的Action,取消注释下面一行
            // needRunMiddleware = needRunMiddleware && !endpoint.Metadata.Any(m => m is AllowAnonymousAttribute);
        }

        if (needRunMiddleware)
        {
            // 这里编写你的中间件核心逻辑,比如请求日志、参数校验等
            Console.WriteLine($"Executing middleware for authorized path: {context.Request.Path}");
        }

        await _next(context);
    }
}

2. 修正中间件在请求管道中的位置

IEndpointFeature只有在路由匹配完成后才会被填充,因此必须将自定义中间件放在UseRouting之后,确保能正确获取到Endpoint信息。调整Program.cs中的管道顺序:

var app = builder.Build();

// 开发环境配置
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseRouting(); // 启用路由匹配

app.UseAuthentication();
// 将自定义中间件放在认证之后、授权之前(或授权之后,根据你的逻辑需求)
app.UseCustomRequestMiddleware();

app.UseAuthorization();

app.MapControllers();

app.Run();

3. 验证效果

  • 带有[Authorize]特性的控制器/Action请求会触发中间件逻辑;
  • 像WeatherForecastController这类无[Authorize]的控制器,中间件会直接跳过,不执行自定义代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:02:39