我正在尝试获取用户当前注册的
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; }
}
我认为您正在寻找
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);
我认为您需要查询 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();
您可以尝试此操作来获取 ApplicationRoles 列表。
List<string> roleNames = UserManager.GetRoles(userId).ToList();
List<ApplicationRole> roles = RoleManager.Roles.Where(r => roleNames.Contains(r.Name)).ToList();