ASP.net Identity 2.1 Get All Users With Roles

How can I get a list of users, including the role name for the user? My application has default tables of the MVC project.

I can extract all users using Identity 2.1 as follows:

Model

public class GetVendorViewModel { public IList<ApplicationUser> Vendors { get; set; } } 

controller

 public ActionResult Index() { var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var roleStore = new RoleStore<IdentityRole>(ac); var roleManager = new RoleManager<IdentityRole>(roleStore); var vendor = roleManager.FindByName("Vendor").Users; var model = new GetVendorViewModel { Vendors = vendor }; return View("~/Views/User/Administrator/Vendor/Index.cshtml", model); } 

This is returning right now:

 [ { UserId: "4f9ed316-a852-45a9-93a8-a337a37b1c74", RoleId: "a17bb59c-285a-43f9-b5ad-65f46f94bb4f" } ] 

This is correct, but I need to display user information such as name, email address, username, etc.

I would like to return a json object as follows:

 [ { UserId: "4f9ed316-a852-45a9-93a8-a337a37b1c74", RoleId: "a17bb59c-285a-43f9-b5ad-65f46f94bb4f" RoleName: "Administrator" User: { name:"Joe Doe", email:" jd@mail.com ", ... } }, { ... } ] 

RoleName is in the AspNetRoles table.

UserId and RoleId are a request from AspNetUserRoles.

Any clues?

+5
source share
1 answer

Identity's UserManager tends to confuse people. Ultimately, users are still just DbSet in your context, so you can use your context, for example, a query for any other object:

 var role = db.Roles.SingleOrDefault(m => m.Name == "role"); var usersInRole = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id)); 

EDIT . Forget about IdentityUser.Roles links instead of IdentityRole . Therefore, you need to get this role first, and then use the role identifier to query your users.

+9
source

Source: https://habr.com/ru/post/1206740/


All Articles