Home > database >  user does not contain the definition of Identity
user does not contain the definition of Identity

Time:04-21

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

CodePudding user response:

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

You can see User in controller enter image description here You can see Identity in controller is below :

enter image description here

User in AccessControlAttribute is below: enter image description here

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: enter image description here

  • Related