Mark Everard

Hello, I'm Mark – a PhD physicist turned technologist / architect.

Impersonating Visitor Groups from Code

without comments

If you require that a particular HttpRequest impersonates one or more Visitor Groups,  then you can do so by adding one of two keys to the current HttpContext.

Before calling the logic to check each criteria in the VisitorGroup; and determining whether the current User is matched to the group, the VisitorGroupRole class will first check if the current HttpContext contains an item called “ImpersonatedVisitorGroupsById” or an item called “ImpersonatedVisitorGroupsByName”. If these items contain either a valid VisitorGroupRole.Id, or VisitorGroupRole.Name respectively, then the current user will be matched to that Visitor Group regardless of whether they match the Criteria rules.

This is used by EPiServer in edit mode, to allow editors to preview pages as viewed by particular Visitor Groups.

Here  is an method that will ensure that users are always evaluated as being in the Visitor Groups specified by id the method’s arguments. (Note, this method uses the MVC ControllerContext to access the current HttpContext. If you are using this method in a WebForms page you’ll need to substitute this for HttpContext.Current


protected void ImpersonateVisitorGroupsById(string[] visitorGroupIds)
{
     var impersonatedGroupsById =
               ControllerContext.HttpContext.Items["ImpersonatedVisitorGroupsById"] as List<string>
                                                                      ?? new List<string>();
     impersonatedGroupsById.AddRange(visitorGroupIds);
     ControllerContext.HttpContext.Items["ImpersonatedVisitorGroupsById"] = visitorGroupIds;
}

Written by mark

May 9th, 2011 at 9:00 am

Posted in ASP.NET,C#,Code,EPiServer