0

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);
    }
}
Community
  • 1
  • 1
VSB
  • 9,825
  • 16
  • 72
  • 145

3 Answers3

1

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.

tmg
  • 19,895
  • 5
  • 72
  • 76
0

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.

Leandro Soares
  • 2,902
  • 2
  • 27
  • 39
0

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;
}
VSB
  • 9,825
  • 16
  • 72
  • 145