Asp MVC: How get roles from ApplicationUser

断了今生、忘了曾经 提交于 2019-12-01 06:34:43

问题


In ASP.NET MVC 5, in a controller, I have take the user that has make the request with:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

With the ApplicationUser instance, how can i get all the Roles of the user?


回答1:


You can get user and assigned roles by using UserManager.

var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

and then you can get your user like you already did, and also you can get roles for particular user by calling GetRoles method

userManager.GetRoles(userId);



回答2:


        List<string> roles = new UserManager().GetRoles(userIdString)).ToList();

below needed classes were created automatically in ASP.NET 4.5 project using VS 2015 using . the file name is IdentityModels.cs.

default 4 Nuget packages are installed including Microsoft.AspNet.WebApi v5.2.3

 public class UserManager : UserManager<ApplicationUser>
    {
        public UserManager()
            : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
        {
        }
    }

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }


public class ApplicationUser : IdentityUser
{
}


来源:https://stackoverflow.com/questions/34975075/asp-mvc-how-get-roles-from-applicationuser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!