[英]List all users in specific role
In ASP.NET Core 2.2 MVC I'm trying to get a list of all users in a specific role.在 ASP.NET Core 2.2 MVC 中,我试图获取具有特定角色的所有用户的列表。
Fx.外汇。 list of all users in role named "Admin":角色名为“Admin”的所有用户的列表:
var idsWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = _db.ApplicationUser.Where(u => idsWithPermission.Contains(u.Id)).ToListAsync();
return(users);
Compiler fails "u.Id" here: idsWithPermission.Contains(u.Id)
编译器在此处失败“u.Id”: idsWithPermission.Contains(u.Id)
Error: Argument 1: Cannot convert from "string" to Microsoft.AspNetCore.Identity.IdentityUser错误:参数 1:无法从“字符串”转换为 Microsoft.AspNetCore.Identity.IdentityUser
This is a newbie questions, so might be very simple for a shark:-) Thanks a lot in advance...这是一个新手问题,所以对于鲨鱼来说可能非常简单:-) 提前非常感谢......
GetUsersInRoleAsync
returns a list of IdentityUser
objects. GetUsersInRoleAsync
返回IdentityUser
对象的列表。 To get a list of IDs, you need to access the Id
property of these objects.要获取 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;
Note that using .Result
on an async
method is not advised, because it can lead to deadlocks.请注意,不建议在async
方法上使用.Result
,因为它可能导致死锁。 Instead use await
and make your method async
.而是使用await
并使您的方法async
。
Also note that depending on your setup, if ApplicationUser
inherits from IdentityUser
and the identity system is correctly configured, GetUsersInRoleAsync
will already return ApplicationUser
objects and you only need to cast them to the correct type:另请注意,根据您的设置,如果ApplicationUser
继承自IdentityUser
并且身份系统配置正确, GetUsersInRoleAsync
将已经返回ApplicationUser
对象,您只需要将它们转换为正确的类型:
// Get a list of users in the role
var usersWithPermission = _userManager.GetUsersInRoleAsync("Admin").Result;
var users = usersWithPermission.OfType<ApplicationUser>();
return users;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.