【问题标题】:Trying to get all roles in Identity试图获得身份中的所有角色
【发布时间】:2014-11-23 14:53:31
【问题描述】:

我正在尝试获取我的应用程序中所有角色的列表。我查看了以下帖子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 方法,但没有成功。

【问题讨论】:

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


    【解决方案1】:

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

    使用var insted of List&lt;string&gt; 或使用List&lt;IdentityRole&gt;

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

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

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

      我个人会使用 var,但在这里包含类型是为了说明返回类型。

      【讨论】:

        【解决方案3】:

        添加它以帮助可能具有自定义类型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> {}
        

        【讨论】:

          【解决方案4】:

          我宁愿不使用 'var',因为它不能用于类范围的字段,并且 if 不能初始化为 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 属性,该属性接收“角色”列表作为值。

          【讨论】:

            【解决方案5】:

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

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

            【讨论】:

              猜你喜欢
              • 2021-10-10
              • 1970-01-01
              • 1970-01-01
              • 2017-02-06
              • 2016-09-05
              • 1970-01-01
              • 1970-01-01
              • 2021-07-12
              • 2016-01-25
              相关资源
              最近更新 更多