Asp MVC:如何从ApplicationUser获取角色

在ASP.NET MVC 5中,在控制器中,我已经使用已发出请求的用户:

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

使用ApplicationUser实例,我如何获得用户的所有角色?

您可以使用UserManager获取用户和分配的角色。

 var userManager = HttpContext.GetOwinContext().GetUserManager(); 

然后你可以像你已经做的那样得到你的用户,你也可以通过调用GetRoles方法获得特定用户的角色

 userManager.GetRoles(userId); 
  List roles = new UserManager().GetRoles(userIdString)).ToList(); 

使用VS 2015在ASP.NET 4.5项目中自动创建下面所需的类。 文件名是IdentityModels.cs

默认安装4个Nuget软件包,包括Microsoft.AspNet.WebApi v5.2.3

  public class UserManager : UserManager { public UserManager() : base(new UserStore(new ApplicationDbContext())) { } } public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext() : base("DefaultConnection") { } } public class ApplicationUser : IdentityUser { }