Asp MVC:如何从ApplicationUser获取角色

5
在ASP.NET MVC 5中,我在控制器中需要获取发起请求的用户:

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

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

2个回答

12
您可以通过使用UserManager来获取用户和分配的角色。
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

然后您可以像以前一样获取用户,还可以通过调用GetRoles方法为特定用户获取其角色

userManager.GetRoles(userId);

0
        List<string> 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<ApplicationUser>
    {
        public UserManager()
            : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
        {
        }
    }

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


public class ApplicationUser : IdentityUser
{
}

2
虽然这段代码片段可能解决了问题,但包括解释真的有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您的代码建议原因。请尽量不要在代码中添加过多的解释性注释,这会降低代码和解释的可读性! - kayess

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接