Get User Roles

Get User Roles

User Roles

  • Retrieves the roles that the user is a member of
  • All strings containing account names must include the domain name in the format domainName\accountName

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Items.Item
  • Sitecore.Security.Accounts.User
  • Sitecore.Security.UserProfile
  • System.Linq

User Roles C# Web Control Code

Sitecore.Data.Items.Item item = this.GetItem();
if (item == null) return;

Sitecore.Security.Accounts.User user = Sitecore.Context.User;
if (user == null) return;

Sitecore.Security.Accounts.UserRoles roles = user.Roles;
if (roles == null) return;

var sortedList = (from entry in roles orderby entry.DisplayName ascending select entry);

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag(); //Div

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and ? for question mark and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P

foreach(var role in sortedList)
    output.Write("{0}", role.DisplayName + "<br/>");

output.RenderEndTag(); //Div

Sources