简体   繁体   中英

user does not contain the definition of Identity

I am Trying to Access a value of Role for some custom Authoration like this string UserRole = ((ClaimsIdentity)User.Identity).FindFirst("RoleId")?.Value; But its giving me error user does not contain the definition of Identity Same thing when I trying access in Another class Its working fine. Can Anybody please tell what I am missing here?

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;
    }

I guess you are in the controller class, so it works.

You can see User in controller 在此处输入图像描述 You can see Identity in controller is below:

在此处输入图像描述

User in AccessControlAttribute is below: 在此处输入图像描述

From the Controller base class, you can get the ClaimsPrincipal from the User property. But if your code is a service class, you can use dependency injection to get an IHttpContextAccessor that lets you get the User from the HttpContext.

1.register IHttpContextAccessor to services

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

2.use dependency injection to get an IHttpContextAccessor that lets you get the User from the 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...
        }
    }

result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM