Ask Your Question
0

How can I retrieve all users belonging to a particular role using ASP.NET Identity?

asked 2023-06-08 01:52:38 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-08 02:11:01 +0000

qstack gravatar image

You can retrieve all users belonging to a particular role using ASP.NET Identity by using the UserManager and RoleManager classes. Here's an example:

  1. Get the role ID of the role you are interested in:
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var roleId = roleManager.FindByName("MyRole").Id;
  1. Use the UserManager to retrieve all users that belong to the role:
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var users = userManager.Users.Where(u => u.Roles.Any(r => r.RoleId == roleId)).ToList();

The Users property of the userManager object will give you all the users in the database. The Where method filters out only those users who have a role with the given role ID. The ToList method converts the filtered users into a list.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-08 01:52:38 +0000

Seen: 14 times

Last updated: Jun 08 '23