orchardcmsorchardcms-1.9

How can I access the current user's roles in Orchard from a view page?


I am trying to get the current user's roles in Orchard 1.9.2 from a view.

I tried this snippet of code but it always returns 0 roles:

var roles = ((ContentItem)WorkContext.CurrentUser.ContentItem).As<UserRolesPart>().Roles;

source: https://www.cloudconstruct.com/blog/retrieving-role-information-in-your-orchard-view-templates

Any ideas?


Solution

  • Perhaps the using statement is missing?

    Try the following code:

    @using Orchard.ContentManagement
    
    @{
      var roles = WorkContext.CurrentUser.As<Orchard.Roles.Models.UserRolesPart>().Roles;
    }
    

    edit 1

    It seems like the user is not authenticated. The line of code posted above creates the following calls:

    1. Orchard.Environment.WorkContextImplementation.GetState("CurrentUser")
    2. Orchard.Environment.WorkContextImplementation.FindResolverForState("CurrentUser")
    3. enumerating through a list of IWorkContextStateProvider, in this list there should be the following implementation: Orchard.Security.CurrentUserWorkContext
    4. Orchard.Security.CurrentUserWorkContext.Get("CurrentUser")
    5. IAuthenticationService.GetAuthenticatedUser() -> which returns the user when authenticated

    So it seems that any of these steps returns without the user. I suggest you create a breakpoint in Orchard.Environment.WorkContextImplementation.GetState() to find out where the issue is.