我试图获取一个角色中所有用户的列表,尽管我在这里阅读了很多问题和链接,但我似乎无法想象这个身份。以下是我目前正在使用的内容:
IdentityRole role = context.Roles.Where(x => x.Name == rolesDDL.SelectedValue).First();
var users = context.Users.Where(x => x.Roles.Any(r => r.RoleId == role.Id));
然而,这会出现错误,表示"序列不包含任何元素"在角色线上。我尝试使用UserManager / RoleManager执行类似的代码,但结果相同:
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = Request.GetOwinContext().GetUserManager<ApplicationRoleManager>();
IdentityRole role = roleManager.Roles.Where(x => x.Name == rolesDDL.SelectedValue).First();
var users = userManager.Users.Where(x => x.Roles.Any(r => r.RoleId == role.Id));
编辑:似乎是RoleManager无法真正找到我的角色的问题。如果我进入ServerExplorer,我可以看到我的AspNetRoles表中的角色,但是在从OWIN上下文实例化我的RoleManager之后,它似乎还没有任何角色。这可能是安装RavenDB数据的问题吗?我看到了如何将用户迁移到Raven,但我希望在我为自己制作更多问题之前首先使用默认设置。
这是我目前在此功能中所拥有的:
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = Request.GetOwinContext().GetUserManager<ApplicationRoleManager>();
//IdentityRole role = roleManager.Roles.Where(x => x.Name == rolesDDL.SelectedValue).First();
//var users = userManager.Users.Where(x => x.Roles.Any(r => r.RoleId == role.
//IdentityRole role = context.Roles.Where(x => x.Name == rolesDDL.SelectedValue).First();
//var users = context.Users.Where(x => x.Roles.Any(r => r.RoleId == role.Id));
var users = roleManager.FindByName(rolesDDL.SelectedItem.Text).Users;
编辑:在startup.auth.cs中找到每个请求的初始值设定项:
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
答案 0 :(得分:0)
如果您使用roleManager
代替并使用角色名称而非角色ID进行过滤,则可以使用以下内容:
var roleManager = HttpContext.Current
.GetOwinContext()
.Get<ApplicationRoleManager>();
var roleName = rolesDDL.SelectedItem.Text;
var users = roleManager.FindByName(roleName).Users