如何在 mvc 5 中获得具有角色的用户

how get just user with roles in mvc 5

我想在 mvc 中获取 just in Role users,我尝试了一切。如您所知,AspNetUserRoles 是一个映射 table(多对多),因此它不会在 EDMX 中生成(按照设计,它没有主键)。我们也不能使用角色table(?)。请考虑我的模型。

这是我最后一次尝试:

    public async Task<ActionResult> Roles()
    {
        var list = context.Users.Include(u => u.Roles);
        var user = new List<ApplicationUser>();
        foreach(var u in list)
        {
            if(u.Roles!= null)
            {
                user.Add(u);
            }
        }     
        return View(user);
    }

这是我的观点:

    @model IEnumerable<Site.Models.ApplicationUser>
      @{
        Layout = null;
       }

       <h2>List of users with Roles:</h2>
       <table class="table">
      <tr>
       <th>
           @Html.DisplayNameFor(model => model.UserName)
       </th>
       <th>
          @Html.DisplayNameFor(model => model.Email)
       </th>
       <th>
          @Html.DisplayNameFor(model => model.Roles)
      </th>
   </tr>
   @foreach (var item in Model)
   {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <th>
            @Html.DisplayFor(modelItem => item.Roles)
        </th>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
            @Html.ActionLink("Details", "Details", new { id = item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Id })
        </td>
    </tr>
  }
   </table>

试试这个:

    var usersList = new List<ApplicationUser>();
    foreach (ApplicationUser user in UserManager.Users)
    {
        var roles = await UserManager.GetRolesAsync(user.Id);
        if(roles.contains("Admin"))
        {
            usersList.Add(user);
        }
    }

这应该只 return 具有管理员角色的用户。希望对你有帮助。

我觉得你应该根据具体的角色来查询。 因为如果稍后添加更多角色,您的应用程序将变得有问题。

public async Task<ActionResult> Roles()
    {
        var user= context.Users.Include(u => u.Roles).Where(u=>u.Roles.Any(r=>r.Name=="RoleName")).ToList();
        return View(user);
    }