public Task InvokeAsync(HttpContext context)
{
// 获取终点路由特性
var endpointFeature = context.Features.Get<IEndpointFeature>();
// 获取是否定义了特性
var attribute = endpointFeature?.Endpoint?.Metadata?.GetMetadata<AllowAnonymousAttribute>();
if (attribute != null)
{
logger.LogInformation($"{context.Request.Path} 无需授权");
}
else
{
logger.LogInformation($"{context.Request.Path} 需要授权");
}
// 调用下一个中间件
return _next(context);
}
注意事项
要想上面操作有效,也就是不为
null
,需要满足以下条件,否则
endpointFeature
返回
null
。
-
启用端点路由
AddControllers()
而不是
AddMvc()
-
UseRouting()
和
UseEndpoints()
之间调用你的中间件