2014-12-03 66 views
2

如何获取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> 

回答

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); 
} 
+0

获取以下错误'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole'不包含'RoleName'的定义,也没有接受'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole'类型的第一个参数的扩展方法'RoleName'可以找到(您是否缺少使用指令或程序集引用?) – Nakib 2014-12-03 20:15:59

+0

请参阅编辑。您需要找出协调员的角色ID。 – Omer 2014-12-03 20:21:06

+0

我如何获得ID? – Nakib 2014-12-03 20:30:28

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); 
    } 

希望这会有所帮助。

相关问题