在我的应用程序中,我有在AspNetUserRoles
保存的角色/角色的用户,而用户根本没有角色。我试图让所有"扮演任何角色"的用户。因此,我试图将所有记录保存在AspNetUserRoles
表中,但是我找不到任何方法可以做到这一点。另外,我不想获取所有用户,然后检查他们是否有任何角色分配给他们,因为这会导致绩效损失。(所有用户中只有1%都有角色。(那么,有什么方法吗?我正在使用.NET Core 2.0。下面的代码:
using Microsoft.AspNetCore.Identity;
using System;
using System.Linq;
namespace GebzeShared.Modules.GUI.Admin.Workflow
{
public class MyClassWorkflow : IMyClassContract
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public MyClassWorkflow(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager
)
{
this._userManager = userManager;
this._roleManager = roleManager;
}
public dynamic GetUserRoleList(ClaimsPrincipal user)
{
try
{
var currentUser = this._userManager.FindByEmailAsync(user.Identity.Name).GetAwaiter().GetResult();
var user2 = this._personnelRepository.Table.FirstOrDefault(x => x.Email == user.Identity.Name);
var userRoleList = this._userManager.Users.Where(x => this._userManager.IsInRoleAsync(currentUser, "anyrole")); //dont want to use this
{
RoleName = role.Name
}).ToList<dynamic>();
return new
{
RoleList = roleList,
};
}
catch (Exception exp)
{
return "Error";
}
}
}
}
而不是查询UserManager
,只需查询User
对象上的角色集。
userManager.Users.Where(u => u.Roles.Any(r => r.RoleName == "anyrole"));
您可以做这样的事情(您需要注入userManger
和roleManager
(:
List<ApplicationUser> usersInRole = new List<ApplicationUser>();
foreach (var role in roleManager.Roles)
{
usersInRole.AddRange(await userManager.GetUsersInRoleAsync(role.Name));
}