Check User exists in a Role in ASP.NET Identity 2.0

By October 29, 2014 MVC One Comment

ASP.NET MVC5 uses Identity 2.0 to manage the users and their roles. There may be scenario to check whether the currently logged in user or any user with the id exists in the given role or not, and checking can be done either in the controller class or in any other class of the application.

Check for the currently logged in user
In a controller you can find whether the currently logged in user exist in a role or not by using User property of the controller class. Type of the User property is IPrincipal and it has a Boolean method IsInRole which takes the role name as input and returns true if the currently logged in user exist in the role.

Check for any user with the id
Another scenario could be to use id of the user to check whether the user exists in the given role or not. GetRoles method of the ApplicationUserManager class returns roles of the user by its id.

Above approach is useful,

  • To check whether any user exists in the role on basis of its id and it is not only limited to the currently logged in user.
  • To check in any other class of the application besides the controller class

Use ApplicationDBContext
Besides the Identity 2.0 classes the ApplicationDbContext class can also be used to check role of the user. You may want to use it, if you have customized the default roles and the users.

In the above code listing,

  1. The logged in user is fetched using User.Identity. To work with the user identity you will have to add the namespace Microsoft.AspNet.Identity.
  2. The Id of the given role is fetched from the Roles table using the ApplicationDbContext
  3. All of the users of the given role are fetched from the Users table using the ApplicationDbContext
  4. As the last step, we are checking whether the logged in user exists in the set of returned users or not.

In these ways you can find whether a user exist in a given role or not. Hope it helps.

Happy Coding.

The following two tabs change content below.
Dhananjay Kumar is a software engineer, consultant, trainer, blogger and speaker from India. He has been a Microsoft MVP since 2010. He can be followed on twitter @debug_mode.