试图获得Identity中的所有角色

时间:2014-11-23 14:53:31

标签: c# asp.net asp.net-identity asp.net-roles

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

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方法但没有成功。

4 个答案:

答案 0 :(得分:17)

查看您的引用链接并自行提问,很明显角色管理器(roleMngr)是IdentityRole的类型,因此如果您尝试获取角色列表,则角色必须是相同的类型。

使用var的{​​{1}}或使用List<string>

List<IdentityRole>

希望这有帮助。

答案 1 :(得分:4)

如果它是您所追求的字符串角色名称列表,则可以执行

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

我个人会使用var,但这里包含的类型用于说明返回类型。

答案 2 :(得分: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> {}

答案 3 :(得分: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 属性,该属性接收“角色”列表作为值。

相关问题