如何访问当前的HttpContext以检查ASP.NET Core 2中基于自定义策略的授权的AuthorizationHandlerContext内的路由和参数?
答案 0 :(得分:19)
您应该将IHttpContextAccessor的实例注入AuthorizationHandler
。
在example的上下文中,可能如下所示:
public class BadgeEntryHandler : AuthorizationHandler<EnterBuildingRequirement>
{
IHttpContextAccessor _httpContextAccessor = null;
public BadgeEntryHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override Task HandleRequirementAsync(
AuthorizationContext context,
EnterBuildingRequirement requirement)
{
HttpContext httpContext = _httpContextAccessor.HttpContext; // Access context here
if (context.User.HasClaim(c => c.Type == ClaimTypes.BadgeId &&
c.Issuer == "http://microsoftsecurity"))
{
context.Succeed(requirement);
return Task.FromResult(0);
}
}
}
您可能需要在DI设置中注册(如果您的某个依赖项还没有),如下所示:
services.AddHttpContextAccessor();
答案 1 :(得分:3)
您可以将IHttpContextAccessor
注入AuthorizationHandler
的构造函数。
e.g。
public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement>
{
private IHttpContextAccessor _contextAccessor;
public MyAuthorizationHandler (IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
MinimumPermissionLevelRequirement requirement) {
var httpContext = _contextAccessor.HttpContext;
// do things
}
}
答案 2 :(得分:1)
无需注射,简单的解决方案!
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
{
var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
var httpContext = authFilterCtx.HttpContext;
}
答案 3 :(得分:0)
如果是 MVC 上下文,您可以从 HttpContext
访问 RouteData
、AuthorizationContext context
以及 MVC 提供的所有其他内容:
var mvcContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
if (mvcContext != null)
{
// Examine MVC specific things like routing data.
}