Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在TypeFilterAttribute中访问usermanager_C#_Asp.net Core - Fatal编程技术网

C# 在TypeFilterAttribute中访问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

我正在ASP.NET Core中创建自定义授权属性。为此,我需要获取我的userroles,我可以在UserManager中找到它。我如何访问它?我可以在我的控制器中得到它,但我想不能在过滤器中

我的代码如下所示:

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
构造函数中解析它