C# 在TypeFilterAttribute中访问usermanager
我正在ASP.NET Core中创建自定义授权属性。为此,我需要获取我的userroles,我可以在UserManager中找到它。我如何访问它?我可以在我的控制器中得到它,但我想不能在过滤器中 我的代码如下所示:C# 在TypeFilterAttribute中访问usermanager,c#,asp.net-core,C#,Asp.net Core,我正在ASP.NET Core中创建自定义授权属性。为此,我需要获取我的userroles,我可以在UserManager中找到它。我如何访问它?我可以在我的控制器中得到它,但我想不能在过滤器中 我的代码如下所示: public class CustomAuthorizeAttribute : TypeFilterAttribute { public CustomAuthorizeAttribute(params string[] roles) : base(typeof(CustomA
public class CustomAuthorizeAttribute : TypeFilterAttribute
{
public CustomAuthorizeAttribute(params string[] roles) : base(typeof(CustomAuthorizeFilter))
{
Arguments = new object[] { roles };
}
}
public class CustomAuthorizeFilter : IAsyncActionFilter
{
private string[] _roles;
public CustomAuthorizeFilter(IReadOnlyList<object> arguments)
{
_roles = (string[])arguments;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var username = context.HttpContext.User.Claims.First().Value;
//var roles = usermanager.
var hasClaim = true;
if (!hasClaim)
{
context.Result = new UnauthorizedResult();
}
else
{
await next();
}
}
}
公共类CustomAuthorizeAttribute:TypeFilterAttribute
{
公共CustomAuthorizeAttribute(参数字符串[]角色):基本(类型(CustomAuthorizeFilter))
{
参数=新对象[]{roles};
}
}
公共类CustomAuthorizeFilter:IAsyncationFilter
{
私有字符串[]_角色;
公共CustomAuthorizeFilter(IReadOnlyList参数)
{
_角色=(字符串[])参数;
}
公共异步任务OnActionExecutionAsync(ActionExecutionContext上下文,ActionExecutionDelegate下一步)
{
var username=context.HttpContext.User.Claims.First().Value;
//var roles=usermanager。
var hasClaim=true;
如果(!hasClaim)
{
context.Result=新的UnauthorizedResult();
}
其他的
{
等待下一个();
}
}
}
由TypeFilterAttribute
修饰的筛选器可以使用内置DI来解析依赖项。例如iLogger工厂
:
public CustomAuthorizeFilter(
IReadOnlyList<object> arguments, //this from attribute params
ILoggerFactory loggerFactory //this from DI
)
{
}
公共自定义过滤器(
IReadOnlyList参数,//此参数来自属性参数
iLogger工厂Logger工厂//来自DI
)
{
}
因此,请确保您的UserManager
已在DI中注册,并在CustomAuthorizeFilter
构造函数中解析它