ASP.NET MVC 3: How to get User's Role in a Controller Method?
Asked Answered
J

3

15

I want to be able to

  1. Get a list of roles of the current authenticated user.
  2. Filter the data provided to that user based on their role.

I see ways to check if the user is in a particular role, but I don't care what role they participate. The database will know what roles are allowed to see what data. I need to submit a collection of these roles to the data service to filter the data based on those roles.

So first step is how do I get all roles associated with the current user in a controller method?

EDIT:

This seemed to work out nicely:

Roles.GetRolesForUser(User.Identity.Name)

Supporting answers still welcome.

Jacoby answered 20/5, 2011 at 3:29 Comment(0)
J
23
Roles.GetRolesForUser(User.Identity.Name)
Jacoby answered 1/6, 2011 at 4:9 Comment(3)
did you answer your own question?Hautegaronne
Well, it was up there forever so I could have either deleted it, or answered it. :)Jacoby
It's preferable for somebody to answer their own question to not having a clearly defined answer when somebody comes searching. Thank you for doing so.Revere
O
13

This can be done with a single statement:

User.IsInRole("admin");
Odel answered 8/1, 2013 at 14:4 Comment(1)
While this does tell you if a user is in a specific role or not, it does not address the original question which asked how to get a list or array of all the user's roles.Feedback
E
10

If anyone need this information, in case your user has many roles but you're looking for one, you could do this:(i thought id share)

@if (Request.IsAuthenticated)
{
   string[] roles = Roles.GetRolesForUser();
   foreach (string role in roles)
   {
       if (role.Contains("admin"))
       {
           <li>@Html.ActionLink("Administration", "Admin", "Movies")</li>
           break;
       }
   }
}
Evangelina answered 10/12, 2012 at 21:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.