Impersonating Visitor Groups from Code

I

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

About the author

Mark Everard

Experienced senior technical manager / architect / lead specialising in digital technologies. Agency and client experience: from pre-sales, pitch and delivery, to strategy, quality assurance and support.

I've worked across the digital industry for the past ten years, helping clients and colleagues across a diverse range of sectors meet numerous digital challenges, specifically focusing on web technologies, digital marketing and content management.

I've worked on large multi-supplier projects and led and managed both in-house and geographically-disperse development teams. And I've always approached my work with a smile on my face.

Mark Everard

Experienced senior technical manager / architect / lead specialising in digital technologies. Agency and client experience: from pre-sales, pitch and delivery, to strategy, quality assurance and support.

I've worked across the digital industry for the past ten years, helping clients and colleagues across a diverse range of sectors meet numerous digital challenges, specifically focusing on web technologies, digital marketing and content management.

I've worked on large multi-supplier projects and led and managed both in-house and geographically-disperse development teams. And I've always approached my work with a smile on my face.

Get in touch