Search code examples
c#asp.netsimplemembership

Get all roles of any user (yes, not currently logged one)


In an MVC app, administrator has a CRUD controller for managing users. Now, the functionality of the edit part needs to be extended and it involves adding a number role dependent tabs. They depend on the role of the viewed user, rather than on roles of the administrator who is viewing them. The easiest way for achieving this, would be getting all roles of that user as a array of strings (or similar), but how do I actually go about obtain those.

Is there a preferred method of getting all roles of a single user in SimpleMembership (based on his UserId) or do I just have to patch up a stored function in the database and pull those through it?

Writing the function is not a big deal, but this problem doesn't sound like something I should have to make workarounds for.


Solution

  • Use the Roles.GetRolesForUser() method https://msdn.microsoft.com/en-us/library/8h930x07(v=vs.110).aspx

    string[] rolesArray = Roles.GetRolesForUser("username"); 
    

    With the string being the User Name of the user as contained in the aspnetdb.

    If you want to find by using a guid, you could try the following:

    Guid userId; // ID of user - you can populate this somehow
    MembershipUser memUser = Membership.GetUser(userId);
    string[] roles = Roles.GetRolesForUser(memUser.UserName);