【问题标题】:Identity Manager How To Get All Users Who Have Any RoleIdentity Manager 如何获取所有具有任何角色的用户
【发布时间】:2018-03-06 00:46:18
【问题描述】:

在我的应用程序中,我的用户的角色/角色保存在 AspNetUserRoles 和根本没有角色的用户。我试图让所有用户“拥有任何角色”。所以,我试图将所有记录保存在AspNetUserRoles 表中,但我找不到任何方法来做到这一点。另外,我不想获取所有用户然后检查他们是否有分配给他们的任何角色,因为这会导致性能损失。 (只有 1% 的用户有角色。)那么,有什么方法可以做到吗?我正在使用.Net Core 2.0。 代码如下:

using Microsoft.AspNetCore.Identity;
using System;
using System.Linq;

namespace GebzeShared.Modules.GUI.Admin.Workflow
{
    public class MyClassWorkflow : IMyClassContract
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;

        public MyClassWorkflow(
            UserManager<ApplicationUser> userManager,
            RoleManager<IdentityRole> roleManager
            )
        {
            this._userManager = userManager;
            this._roleManager = roleManager;
        }

        public dynamic GetUserRoleList(ClaimsPrincipal user)
        {
            try
            {
                var currentUser = this._userManager.FindByEmailAsync(user.Identity.Name).GetAwaiter().GetResult();
                var user2 = this._personnelRepository.Table.FirstOrDefault(x => x.Email == user.Identity.Name);
                var userRoleList = this._userManager.Users.Where(x => this._userManager.IsInRoleAsync(currentUser, "anyrole")); //dont want to use this
                {
                    RoleName = role.Name
                }).ToList<dynamic>();

                return new
                {
                    RoleList = roleList,
                };
            }
            catch (Exception exp)
            {
                return "Error";
            }
        }
    }
}

【问题讨论】:

    标签: c# asp.net-core asp.net-identity


    【解决方案1】:

    无需查询UserManager,只需查询User 对象上的角色集。

    userManager.Users.Where(u =&gt; u.Roles.Any(r =&gt; r.RoleName == "anyrole"));

    【讨论】:

      【解决方案2】:

      你可以这样做(你需要注入userMangerroleManager):

      List<ApplicationUser> usersInRole = new List<ApplicationUser>();
      foreach (var role in roleManager.Roles)
      {
          usersInRole.AddRange(await userManager.GetUsersInRoleAsync(role.Name));
      }
      

      【讨论】:

        猜你喜欢
        • 2015-01-09
        • 2013-10-29
        • 1970-01-01
        • 2014-03-08
        • 2021-10-06
        • 1970-01-01
        • 2021-02-24
        • 2023-03-21
        • 2021-12-22
        相关资源
        最近更新 更多