get current user's role

前端 未结 7 1892
逝去的感伤
逝去的感伤 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:46

    if you want to get the role name of any user, then simply use following two functions in the controller you want to perform action .

    public ApplicationSignInManager SignInManager
            {
                get { return _signInManager ?? HttpContext.GetOwinContext().Get(); }
                private set { _signInManager = value; }
            }
    
            public ApplicationUserManager UserManager
            {
                get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); }
                private set { _userManager = value; }
            }
    

    and then in the action , use the following line .

    var role = UserManager.GetRoles(UserId);
    

    note that here UserId is the id of ApplicationUser.

    this role will be IList

    if your application logic is such that a user can be in only one role then you can access it by

    string roleName = role[0];
    

提交回复
热议问题