4 回答
TA贡献1804条经验 获得超3个赞
我能够通过在AuthorizationHandlerContext
中使用来获取 .NET Core 3.1 中的自定义属性。ControllerActionDescriptor
private IEnumerable<TAttribute> GetAttributes<TAttribute>(AuthorizationHandlerContext authContext)
{
if (authContext.Resource is RouteEndpoint routeEndpoint)
{
var actionDescriptor = routeEndpoint.Metadata.OfType<ControllerActionDescriptor>().SingleOrDefault();
var attributes = actionDescriptor?.MethodInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
return attributes;
}
return null;
}
TA贡献1829条经验 获得超7个赞
从 .net 5 开始,上下文是HttpContext
有GetEndPoint
方法扩展HttpContext
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
if(context is HttpContext httContext){
var endpoint = context.GetEndPoint();
} else {
throw ... // let's see how things will move with next version of .net
}
}
TA贡献1798条经验 获得超7个赞
有一个部分“在处理程序中访问 MVC 请求上下文”,但这是错误的。
然而,在“反馈”下,他们的 2 个问题看起来与最有希望的答案相关,即将下面的代码添加到AuthorizationHandler
.
这可以访问controllerActionDescriptor
,但正如你所看到的,我已经查看了各种属性,但没有一个属性给我当前的路由数据:
var controllerActionDescriptor = routeEndpoint.Metadata
.OfType<ControllerActionDescriptor>()
.SingleOrDefault();
if (controllerActionDescriptor != null)
{
var a = controllerActionDescriptor.AttributeRouteInfo;
var p = controllerActionDescriptor.Parameters;
var ep = controllerActionDescriptor.EndpointMetadata;
var r = controllerActionDescriptor.RouteValues;
}
TA贡献1810条经验 获得超4个赞
我找到了解决方案,在ConfigureServices中将IHttpContextAccessor注册到IOC中
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
然后在AttributeAuthorizationHandler中获取
public class AccountLoginAuthorizeHandler : AttributeAuthorizationHandler<AccountLoginAuthorizationRequirement, AccountLoginAttribute>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public PermissionAuthorizeHandler(IHttpContextAccessor httpContextAccessor, IZaabeeRedisClient redisClient,
IOptions<LoginConfig> loginConfig)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccountLoginAuthorizationRequirement requirement, IEnumerable<AccountLoginAttribute> attributes)
{
if (context.Resource is AuthorizationFilterContext filterContext)
{
var httpContext = _httpContextAccessor.HttpContext;
//Do Something
}
else
//Do Something
context.Succeed(requirement);
return Task.CompletedTask;
}
}
- 4 回答
- 0 关注
- 219 浏览
添加回答
举报