.NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证

.NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证_第1张图片

        public Task InvokeAsync(HttpContext context)
        {
            // 获取终点路由特性
            var endpointFeature = context.Features.Get();
            // 获取是否定义了特性
            var attribute = endpointFeature?.Endpoint?.Metadata?.GetMetadata();
            if (attribute != null)
            {
                logger.LogInformation($"{context.Request.Path} 无需授权");
            }
            else
            {
                logger.LogInformation($"{context.Request.Path} 需要授权");
            }

            // 调用下一个中间件
            return _next(context);
        }

注意事项

要想上面操作有效,也就是不为 null,需要满足以下条件,否则 endpointFeature 返回 null

  • 启用端点路由 AddControllers() 而不是 AddMvc()
  • UseRouting() 和 UseEndpoints() 之间调用你的中间件

 

.NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证_第2张图片

 .NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证_第3张图片

你可能感兴趣的:(.net)