Asp MVC:如何从ApplicationUser获取角色

Tom*_*Tom 3 .net c# asp.net-mvc owin asp.net-mvc-5

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

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

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

IMu*_*gic 8

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

var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Run Code Online (Sandbox Code Playgroud)

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

userManager.GetRoles(userId);
Run Code Online (Sandbox Code Playgroud)