如何获取用户在MVC 5中注册的角色的ID

Zap*_*ica 4 asp.net asp.net-mvc user-roles asp.net-mvc-5 asp.net-identity

我正在尝试获取IList<ApplicationRole>用户当前注册的角色.

现在在Usermanager类中,我看到有一个函数调用IList<String> usersRoles = userManager.GetRoles(id);但它只是将Role的名称作为字符串返回.这并不能帮助我,我需要的id,namedescription中的作用.

我怎样才能进行类似的调用但是收到applicationRole而不是字符串?

这是我的模特:

   public class ApplicationRole : IdentityRole
{
    [Display(Name = "Description")]
    [StringLength(100, MinimumLength = 5)]
    public string Description { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

Chr*_*att 9

我想你在找RoleManager.它在形式和功能上非常相似UserManager,但专门用于具有角色的CRUD.

var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
Run Code Online (Sandbox Code Playgroud)

context你的实例在哪里DbContext

然后,你可以这样做:

var role = await RoleManager.FindByIdAsync(roleId);
Run Code Online (Sandbox Code Playgroud)

要么

var role = await RoleManager.FindByNameAsync(roleName); 
Run Code Online (Sandbox Code Playgroud)


Ant*_*Chu 8

我认为您需要查询ApplicationDbContext,因为没有明显的方法可以通过UserManager或者来自UserStoreAPI 的单个调用来获取它...

var context = new ApplicationDbContext();
var roles = await context.Users
                    .Where(u => u.Id == userId)
                    .SelectMany(u => u.Roles)
                    .Join(context.Roles, ur => ur.RoleId, r => r.Id, (ur, r) => r)
                    .ToListAsync();
Run Code Online (Sandbox Code Playgroud)