c# - 查找具有特定角色的用户

标签 c# asp.net-mvc asp.net-identity user-roles

我的代码是:

public async Task<ActionResult> Index()
{
    var teaching = db.Teachings.Include(d =>d.Course).Include(d=>d.Group).Include(d => d.User);

    return View(await teaching.ToListAsync());
}

我想知道如何过滤某些角色,我的意思是,如果可以的话,如何仅过滤具有特定角色的用户。

我认为可能的解决方案可能是 ....Include(d => d.Users).Where(...),但我不知道如何比较我正在使用的具有特定角色的用户。

我的角色是教师、管理员或学生。

总之,只过滤角色为“老师”的用户。

最佳答案

假设您正在使用 ASP.net 提供的身份框架,您可以仅使用 UserManager 来实现这一点。

在UserManager中,有一个函数适合您,那就是GetUsersInRoleAsync(string roleName)。这将返回给您该角色的用户列表。

你可以这么做

var userThatYouWant = await _userManager.GetUsersInRoleAsync("RoleName");

瞧,该列表将包含具有您指定角色的所有用户。

这是假设您是否已正确初始化 _userManager。

关于c# - 查找具有特定角色的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44301484/

相关文章:

c# - 如何从 Web API post 返回一个新类型?

c# - 如何在 ASP.Net MVC 应用程序中引用引导库

c# - 无法使 MvcMiniProfiler 与 EF4.1 和我们的存储库模式一起使用

.net - 无法从 GenericIdentity 检索角色

c# - 满足 ASP.NET Core 中的 UserManager 依赖项需要什么要求?

c# - 在 ASP.NET formview 上,什么时候引发 ModeChanged 和 ModeChanging 事件?

c# - 使用数据协定将 JSON 转换为 C# 对象 - 我在这里缺少什么?

c# - 返回带有错误状态码 MVC 的 JSON

asp.net-core - 如何修改.Aspnetcore.Identity.Application Cookie名称?

c# - WebApi HttpPost 无法在 Windows Azure 上运行