Trying to get all roles in Identity

筅森魡賤 提交于 2019-12-22 04:01:30

问题


I am trying to get a list of all the roles in my application. I have looked at the following post Getting All Users... and other sources. Here is my code which I think is what I am supposed to do.

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

However, I’m getting the following error: Cannot implicitly convert type GenericList(IdentityRole) to List(string). Any suggestions? I am trying to get the list so I can populate a dropdown list on a registration page to assign a user to a particular role. Using ASPNet 4.5 and identity framework 2 (I think).

PS I’ve also tried the Roles.GetAllRoles method with no success.


回答1:


Looking at your reference link and question it self, it is clear that the role manager (roleMngr) is type of IdentityRole, so that roles has to be the same type if you trying to get the list of roles.

Use var insted of List<string> or use List<IdentityRole>.

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

var roles = roleMngr.Roles.ToList();

Hope this helps.




回答2:


If it's a list of string role names you're after, you could do

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

I would personally use var, but included the type here to illustrate the return type.




回答3:


Adding this to help others who may have a custom type Identity (not the default string). If you have, let's say int, you can use this:

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> {}


来源:https://stackoverflow.com/questions/27090227/trying-to-get-all-roles-in-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!