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

问题描述 投票:0回答:3

我正在尝试获取用户当前注册的

IList<ApplicationRole>
角色。

现在在

UserManager
类中,我看到有一个名为
GetRolesAsync()
的函数,但它只返回角色名称列表
IList<String>
。这对我没有帮助,因为我不仅需要
Name
属性,还需要角色的
Id
Description
属性。

如何拨打类似的电话,但收到

IList<ApplicationRole>
角色列表,而不是
IList<String>
角色名称?

应用程序角色

public class ApplicationRole : IdentityRole
{
    [Display(Name = "Description")]
    [StringLength(100, MinimumLength = 5)]
    public string Description { get; set; }
}
asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity user-roles
3个回答
11
投票

我认为您正在寻找

RoleManager
。它在形式和功能上与
UserManager
非常相似,但专门用于具有角色的 CRUD。

var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

其中

context
是您的
DbContext
的实例。

然后,你可以这样做:

var role = await RoleManager.FindByIdAsync(roleId);

或者

var role = await RoleManager.FindByNameAsync(roleName); 

10
投票

我认为您需要查询 ApplicationDbContext 来获取它,因为没有明显的方法可以通过

UserManager
UserStore
API 进行一次调用来获取它...

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();

1
投票

您可以尝试此操作来获取 ApplicationRoles 列表。

 List<string> roleNames = UserManager.GetRoles(userId).ToList();

 List<ApplicationRole> roles = RoleManager.Roles.Where(r => roleNames.Contains(r.Name)).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.