繁体   English   中英

如何使所有用户脱离特定角色

[英]How to get all the users from an specific role

我的Users分为两类: StudentProfessor ,我试图使所有用户都处于“ Professor角色内,但是我不知道自己在做什么错。

这是我尝试执行的代码:

RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
List<IdentityUserRole> professors = roleManager.FindByName("Professor").Users.ToList();

List<AppUser> users = new List<AppUser>();

foreach(IdentityUserRole iuser in professors)
{
    AppUser user = manager.FindById(iuser.UserId);
    users.Add(user);
}

Professors由于某种原因仍然无效。 有人可以帮我吗?

我怀疑是否已经为此目的内置了功能,但是您可以通过这种方式获得用户:

public async Task GetUsersInRole()
{
    ApplicationDbContext context = new ApplicationDbContext();
    var roles = context.Roles.Where(r => r.Name == "Professor");
    if (roles.Any())
    {
        var users = await UserManager.Users.ToListAsync();
        var result = (from c in users
                       where c.Roles.Any(r => r.RoleId == roles.First().Id)
                       select c);
    }
}

并调用如下方法:

public async Task<ActionResult> Index()
{
    await GetUsersInRole();
    return View();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM