This technical article was first published over 2 years ago and may discuss features and approaches that are no longer relevant for the current version of the platform.

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 a 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;
}