Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ASP.NET Identity users by role

I created a new MVC project with ASP.NET Identity as my authentication and authorization framework, using the individual authentication method. I successfully added 3 roles to the application: Admin, Customer, Owner.

Now I've made three action methods in my HomeController: "All Admins", "All Customers", "All Owners". How can I, in each action method, display the users that are in each role and their total count? Meaning when I click on "All Admins" it display all users with admin roles, and the same with the "All Customers" and "All Owners" actions.

like image 812
Umer Waqar Avatar asked Sep 16 '25 02:09

Umer Waqar


1 Answers

You can use the RoleManager and UserManager. The latter lets you query on RoleId only, so you'll have to look up the Role first:

// Look up the role
string roleName = "Admin";
var role = await _roleManager.Roles.SingleAsync(r => r.Name == roleName);

// Find the users in that role
var roleUsers = _userManager.Users.Where(u => u.Roles.Any(r => r.RoleId == role.Id));

Now you can send the roleUsers to a view that displays the users and their total count.

like image 125
CodeCaster Avatar answered Sep 17 '25 18:09

CodeCaster