简体   繁体   中英

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.

I need to mention that ApplicationUser is an extention of 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.

Inside that BaseController you can instantiate the ApplicationManager and create a method that optionally receives an ID (UserId) and returns a bool.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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