user 不包含 Identity 的定义

user does not contain the definition of Identity

我正在尝试像这样访问某些自定义授权的角色值 string UserRole = ((ClaimsIdentity)User.Identity).FindFirst("RoleId")?.Value; 但是它给我错误 user does not contain the definition of Identity 当我尝试在另一个中访问时也是如此 class 它正在工作美好的。谁能告诉我这里缺少什么?

AccessControlAttribute.cs

public class AccessControlAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public string Role;
    
    string UserRole = ((ClaimsIdentity)User.Identity).FindFirst("RoleId")?.Value;
    public AccessControlAttribute(string Role):base(Role)
    {
        if (Role == "Admin".ToLower())
        {
            this.Role = "2";
        }
        else
            this.Role = "1";
        // this._role = Role;
    }

我猜你在控制器中 class,所以它有效。

控制器中可以看到User 您可以在控制器中看到 Identity 如下:

AccessControlAttribute 中的

User 如下:

从控制器库 class,您可以从用户 属性 获得 ClaimsPrincipal。但是如果你的代码是一个服务 class,你可以使用依赖注入来获取一个 IHttpContextAccessor,它可以让你从 HttpContext 中获取用户。

1.register IHttpContextAccessor 服务

 public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHttpContextAccessor();
}

2.use 依赖注入以获取 IHttpContextAccessor,使您可以从 HttpContext 获取用户。

public class AccessControlAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public AccessControlAttribute(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        public string Role;
       
        public AccessControlAttribute(string Role) : base(Role)
        {
            var User = _httpContextAccessor.HttpContext.User;
            string UserRole = ((ClaimsIdentity)User.Identity).FindFirst("RoleId")?.Value;
            if (Role == "Admin".ToLower())
            {
                this.Role = "2";
            }
            else
                this.Role = "1";
            // this._role = Role;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            throw new System.NotImplementedException();//do your staff...
        }
    }

结果: