get current user's role

前端 未结 7 1910
逝去的感伤
逝去的感伤 2020-12-29 20:11

Is there any way to get the explicit role that a user belongs to in my controller? This assumes using ASP.NET Membership and Role Providers. \"IsInRole\" doesn\'t work - I n

7条回答
  •  我在风中等你
    2020-12-29 20:44

    I don't know if I'm missing some weird setting or setup, but I cannot get e.g. User.IsInRole or Roles.GetRolesForUser() to work. I just get an exception (I think null reference), and the application just halts. Even though I have configured a RoleManager to the OwinContext and a Create method etc. like in the Identity Sample project by Microsoft, as well as enabled Role Manager in web.config. I solved this at first using another approach, like this (db is the ApplicationDbContext):

    var UserID = User.Identity.GetUserId();    
    var userRoles = db.Roles.Include(r => r.Users).ToList();
    
    var userRoleNames = (from r in userRoles
                                from u in r.Users
                                where u.UserId == UserID
                                select r.Name).ToList();
    

    This may not be the most optimized way and can possibly be altered to a simplier form but it worked for me and may not require as much setup/dependencies as other approaches. The second approach is this (add this to your controller class):

        private ApplicationDbContext db = new ApplicationDbContext();
        private ApplicationUserManager _userManager;
        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager();
            }
            set
            {
                _userManager = value;
            }
        }
    
        private ApplicationRoleManager _roleManager;
        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get();
            }
            private set
            {
                _roleManager = value;
            }
        }
    

    Inside your controller you can now do e.g.:

    var UserID = User.Identity.GetUserId();
    var RolesForUser = await UserManager.GetRolesAsync(UserID);
    

    I'm using ASP.NET MVC 5 application just to be clear. The RoleManager isn't used in this example but it can be used for creating, finding, updating etc. roles. Using this approach allows for async calls using await, in case that is a benefit for your application.

提交回复
热议问题