列出特定角色的所有用户

List all users in specific role

在 ASP.NET Core 2.2 MVC 中,我正在尝试获取具有特定角色的所有用户的列表。
外汇。角色名为 "Admin":

的所有用户的列表
var idsWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = _db.ApplicationUser.Where(u => idsWithPermission.Contains(u.Id)).ToListAsync();
return(users);

编译器在此处失败 "u.Id":idsWithPermission.Contains(u.Id)

Error: Argument 1: Cannot convert from "string" to Microsoft.AspNetCore.Identity.IdentityUser

这是一个新手问题,所以对于鲨鱼来说可能非常简单:-) 非常感谢...

GetUsersInRoleAsync return 是 IdentityUser 个对象的列表。要获取 ID 列表,您需要访问这些对象的 Id 属性。

// Get a list of users in the role
var usersWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;

// Then get a list of the ids of these users
var idsWithPermission = usersWithPermission.Select(u => u.Id);

// Now get the users in our database with the same ids
var users = _db.ApplicationUser.Where(u => idsWithPermission.Contains(u.Id)).ToListAsync();

return users;

请注意,不建议在 async 方法上使用 .Result,因为它会导致死锁。而是使用 await 并使您的方法 async.


另请注意,根据您的设置,如果 ApplicationUser 继承自 IdentityUser 并且身份系统配置正确,GetUsersInRoleAsync 已经 return ApplicationUser 对象,你只需要将它们转换为正确的类型:

// Get a list of users in the role
var usersWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = usersWithPermission.OfType<ApplicationUser>();

return users;