How do you check in code if a request matches an EPiServer Visitor Group

1.1k Views Asked by At

We've set up a new "visitor group" in EPiServer 6r2, and we want to add a css class to the <body> tag of the site if the user is in that group, so different groups get different site designs. I'm trying to find out if the current visitor is in a matching group in the code-behind of a masterpage file in order to add this extra class and can't get the below code to return anything but false.

I'm not sure if the role name mentioned is the name you enter in the CMS UI when adding a visitor group.

Paul Smith blogged a proposed solution to this but I haven't been able to get it to return anything but false yet, and judging by the only comment on the blog article I'm not alone. Code sample #1 from this link (which is the one I'm using):

 using EPiServer.Personalization.VisitorGroups;
 ...
 bool match = EPiServer.Security.PrincipalInfo.CurrentPrincipal
              .IsInRole("My Visitor Group", SecurityEntityType.VisitorGroup);

I found the developer guide to membership and role providers which states that replacePrincipal must be set to true for the correct principal to be in place. I checked and this is already the case for my config.


Documentation

Oddly I searched the 6r2 documentation from http://sdk.episerver.com/ and can't find the documentation for IPrincipalExtensions at all, even though I see the class in object browser in 6.2. in my sln. Details: Assembly EPiServer.ApplicationModules - C:\Windows\assembly\GAC_MSIL\EPiServer.ApplicationModules\6.2.267.1__8fe83dea738b45b7\EPiServer.ApplicationModules.dll - public static bool IsInRole(this System.Security.Principal.IPrincipal principal, string role, EPiServer.Security.SecurityEntityType type) Member of EPiServer.Personalization.VisitorGroups.IPrinicipalExtensions


Please comment if you spot errors or I've missed anything as coding for EPiServer is a bit of a fog-of-war affair and I'm a little battle-weary.

1

There are 1 best solutions below

0
On BEST ANSWER

Found it by browsing the object model and guessing. So much for documentation.

using EPiServer.Personalization.VisitorGroups;
using EPiServer.Security;

const string visitorGroupName = "Some users";
var groupHelper = new VisitorGroupHelper();
bool isPrincipalInGroup = groupHelper.IsPrincipalInGroup(
           PrincipalInfo.CurrentPrincipal, visitorGroupName);

Tested and working in EPiServer 6r2 (aka 6.1).

String visitorGroupName must match the string entered into the "Name" box on the EPiServer admin interface when creating / editing the visitor group. See screenshot below:

enter image description here