简体   繁体   English

ASP.Net MVC5:一种获得特定角色用户列表的有效方法

[英]ASP.Net MVC5: Efficient method to get list of user in specific role

Using this answer , I implemented below code to get list of ApplicationUsers in a specific role. 使用此答案 ,我实现了以下代码,以获取特定角色的ApplicationUsers列表。

I need to mention that ApplicationUser is an extention of IdentityUser. 我需要提到ApplicationUser是IdentityUser的扩展。 I want to know are there any better methods for this? 我想知道还有更好的方法吗?

ApplicationDbContext context = new ApplicationDbContext();
var store = new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(dbContext);
var manager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(store); 
List<ApplicationUser>  users = new List<ApplicationUser>();
foreach (ApplicationUser user in manager.Users.ToList())
{
    if (manager.IsInRole(user.Id,"Admin")){
        users.Add(user);
    }
}

You can query like this 你可以这样查询

ApplicationDbContext context = new ApplicationDbContext();
var role = context.Roles.SingleOrDefault(m => m.Name == "Admin");
var usersInRole = context.Users.Where(m => m.Roles.Any(r => r.RoleId != role.Id));

I am not sure if this is the optimal way, but does less queries to database than your code. 我不确定这是否是最佳方法,但是对数据库的查询少于您的代码。

No, there isn't better way. 不,没有更好的方法。

But assuming you are using that in your controller you could create a BaseController where every other controller is derived from. 但是,假设您在控制器中使用该控件,则可以创建一个BaseController,所有其他控制器都从该控制器派生。

Inside that BaseController you can instantiate the ApplicationManager and create a method that optionally receives an ID (UserId) and returns a bool. 在该BaseController内,您可以实例化ApplicationManager并创建一个方法,该方法可以选择接收ID(UserId)并返回布尔值。

Which you could call in your controller like this: 您可以在控制器中这样调用:

if(HasRole("Owner")) {} // CurrentUser
if(HasRole(Id, "Owner")) {} // Specific User

There are other ways, but that's a developer choise. 还有其他方法,但这是开发人员的选择。

Note 注意

Keep in mind that if you choose to statically instantiate the ApplicationManager, it will run only once which may do things that you don't want, like adding a user to a specific role and that ApplicationManager not showing the new role unless it is created again. 请记住,如果您选择静态实例化ApplicationManager,它将仅运行一次,这可能会执行您不想要的事情,例如将用户添加到特定角色,以及ApplicationManager除非再次创建,否则不会显示新角色。 。

I suggest below method: 我建议以下方法:

public static bool isInRole(IPrincipal User, string roleName, ApplicationDbContext dbContext)
{
    try
    {
        var store = new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(dbContext);
        var manager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(store);
        return manager.IsInRole(User.Identity.GetUserId(), roleName);

    }
    catch (Exception ex)
    {
        return false;
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM