尝试获取身份中的所有角色

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

我正在尝试获取我的应用程序中所有角色的列表。我查看了以下帖子获取所有用户...和其他来源。这是我的代码,我认为这是我应该做的。

var roleStore = new RoleStore<IdentityRole>(context)
var roleMngr  = new RoleManager<IdentityRole>(roleStore);
List<string> roles = roleMngr.Roles.ToList();

但是,我收到以下错误:无法将类型

GenericList(IdentityRole)
隐式转换为
List(string)
。有什么建议么?我正在尝试获取该列表,以便可以在注册页面上填充下拉列表以将用户分配给特定角色。使用 ASPNet 4.5 和身份框架 2(我认为)。

PS我也尝试过Roles.GetAllRoles方法,但没有成功。

c# asp.net asp.net-identity asp.net-roles
5个回答
32
投票

查看您的参考链接并自我提问,很明显角色管理器(

roleMngr
)是
IdentityRole
的类型,因此如果您尝试获取角色列表,
roles
必须是相同的类型.

使用

var
代替
List<string>
或使用
List<IdentityRole>

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

var roles = roleMngr.Roles.ToList();

8
投票

如果它是您想要的字符串角色名称列表,您可以这样做

List<string> roles = roleMngr.Roles.Select(x => x.Name).ToList();

我个人会使用 var,但在此处包含类型以说明返回类型。


3
投票

dotnet5
我只是用了这个
RoleStore
而不需要
RoleManager

var roleStore = new RoleStore<IdentityRole>(_context);
List<IdentityRole> roles = roleStore.Roles.ToList();

1
投票

添加此内容是为了帮助其他可能拥有自定义类型

Identity
(不是默认
string
)的人。 如果你有,比如说
int
,你可以使用这个:

var roleStore = new RoleStore<AppRole, int, AppUserRole>(dbContext);
var roleMngr = new RoleManager<AppRole, int>(roleStore);

public class AppUserRole : IdentityUserRole<int> {}
public class AppRole : IdentityRole<int, AppUserRole> {}

0
投票

我宁愿不使用“var”,因为它不能在类范围内的字段上使用,并且不能初始化为 null 以及许多其他限制。无论如何,这会更干净,并且对我有用:

RoleStore<IdentityRole> roleStore = new RoleStore<IdentityRole>(_context);
RoleManager<IdentityRole> roleMngr = new RoleManager<IdentityRole>(roleStore);
List<IdentityRole> roles = roleMngr.Roles.ToList();

然后您可以将列表“角色”转换为任何类型的列表(只需将其转换为 string 列表或 SelectListItem 列表),例如在这种情况下,如果您想将其显示在这样的选择标签中:

 <select class="custom-select" asp-for="Input.Role" asp-items="
 Model._Roles"> </select>

您可以将“_Roles”定义为

RegisterModel
属性,该属性接收“角色”列表作为值。

© www.soinside.com 2019 - 2024. All rights reserved.