如何获取特定角色的用户列表?

时间:2014-12-03 19:11:59

标签: c# asp.net-mvc-5 asp.net-membership asp.net-identity

如何获取ASP.net MVC5中特定角色的用户列表。我有以下代码,但它返回所有用户。

 public ActionResult Index()
  {
        var users = Context.Users.ToList();
        return View(users);
  }

我有角色名称"协调员"。我只想要拥有该角色的所有用户。

//查看文件

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
@{
    ViewBag.Title = "Index";
}

<h2>Roles Listing </h2>
<div>
    <p><strong>Username | Email</strong></p>
    @foreach (var user in Model)
    {
        <p>
            @user.UserName   |   @user.Email | @Html.ActionLink("Delete", "Delete", new { id = user.Id })
        </p>
    }
</div>

2 个答案:

答案 0 :(得分:1)

假设每个用户实例都是ApplicationUser类型,并且您实现了基于角色的身份验证,则可以轻松过滤具有特定角色的用户,如下所示:

public ActionResult Index()
{
        // Assuming that Coordinator has RoleId of 3
        var users = Context.Users.Where(x=>x.Roles.Any(y=>y.RoleId == 3)).ToList();
        return View(users);
}

答案 1 :(得分:0)

首先创建ApplicationRoleManager类来管理如下角色。

    public class ApplicationRoleManager : RoleManager<IdentityRole, string>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
            : base(roleStore)
        {
        }

        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            return new ApplicationRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<ApplicationDbContext>()));
        }
    }

然后将以下代码添加到Startup.Auth.cs类,以便在owin启动期间创建RoleManager的实例。

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

您的控制器操作应该是这样的。

  public ActionResult Index()
  {
        var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        var users = roleManager.FindByName("Coordinator").Users;

        return View(users);
  }

希望这有帮助。

相关问题