ASP.net Identity 2.1获取具有角色的所有用户 [英] ASP.net Identity 2.1 Get all users with roles

查看:108
本文介绍了ASP.net Identity 2.1获取具有角色的所有用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取用户列表,包括每个用户的角色名称? 我的应用程序具有MVC项目的默认表.

How can I get a list of users including the role name per user? My app has the default tables of an MVC Project.

我能够使用Identity 2.1检索所有用户,如下所示:

I'm able to retrieve all users using Identity 2.1 like this:

型号

public class GetVendorViewModel
{
    public IList<ApplicationUser> Vendors { get; set; }
}

控制器

public ActionResult Index()
        {

            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var roleStore = new RoleStore<IdentityRole>(ac);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var vendor = roleManager.FindByName("Vendor").Users;
            var model = new GetVendorViewModel { Vendors = vendor };
            return View("~/Views/User/Administrator/Vendor/Index.cshtml", model);
        }

现在返回此:

[
   {
      UserId: "4f9ed316-a852-45a9-93a8-a337a37b1c74",
      RoleId: "a17bb59c-285a-43f9-b5ad-65f46f94bb4f"
   }
]

这是正确的,但我需要显示用户信息,例如姓名,电子邮件,用户名等.

This is correct but I need to display the user information such as name, email, username etc.

我想返回一个这样的json对象:

I would like to return a json object like this:

[
  {
    UserId: "4f9ed316-a852-45a9-93a8-a337a37b1c74",
    RoleId: "a17bb59c-285a-43f9-b5ad-65f46f94bb4f"
    RoleName: "Administrator"
    User: {
            name:"Joe Doe",
            email:"jd@mail.com",
            ...
          }
  },
  {
    ...
  }
]

角色名称在表AspNetRoles中.

RoleName is in the table AspNetRoles.

UserId和RoleId是从AspNetUserRoles查询的.

UserId and RoleId its being query from AspNetUserRoles.

有任何线索吗?

推荐答案

Identity中的UserManager内容容易使人们感到困惑.最终,用户仍然只是上下文中的DbSet,因此您可以像查询其他任何对象一样使用上下文:

The UserManager stuff in Identity tends to confuse people. Ultimately, users are still just a DbSet on your context, so you can use your context like querying for any other object:

var role = db.Roles.SingleOrDefault(m => m.Name == "role");
var usersInRole = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id));

编辑忘记了IdentityUser.Roles直接引用IdentityUserRole而不是IdentityRole.因此,您需要先获取角色,然后使用角色的ID来查询用户.

EDIT Forgot that IdentityUser.Roles references IdentityUserRole instead of IdentityRole directly. So you need to get the role first, and then use the role's id to query into your users.

这篇关于ASP.net Identity 2.1获取具有角色的所有用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆