Trying to get all roles in Identity

In dotnet5 I just used this RoleStore without needing RoleManager

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

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.


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

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.