Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using EPiServer.Core;
using EPiServer.Personalization.VisitorGroups;
using EPiServer.ServiceLocation;
using EPiServer.Tracking.Cms;
using EPiServer.Tracking.Core;
using EPiServer.Web;
using EPiServer.Web.Routing;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace Foundation.Infrastructure.Tracking
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = false)]
public class VisitorGroupTrackingAttribute : ActionFilterAttribute
private readonly Injected<ITrackingService> _trackingService;
private readonly Injected<IContextModeResolver> _contextModeResolver;
private readonly Injected<IContentRouteHelper> _routeHelper;
private readonly Injected<IVisitorGroupRepository> _visitorGroupRepo;
//Called before the Action method (Controller) executes.
public override void OnActionExecuting(ActionExecutingContext filterContext)
IContent content = this._routeHelper.Service.Content;
if (content == null || !this.PageIsInViewMode())
HttpContextBase httpContext = filterContext.HttpContext;
//Store matched and unmatched visitor groups
var matchedVGs = new List<string>();
var unmatchedVGs = new List<string>();
//Helper class to check visitor group membership
var vgHelper = new VisitorGroupHelper();
//All visitor groups defined at current website
var visitorGroups = _visitorGroupRepo.Service.List();
foreach (var visitorGroup in visitorGroups)
//Check if current user/visitor is member of visitor group
if (vgHelper.IsPrincipalInGroup(httpContext.User, visitorGroup.Name))
//Episerver standard tracking data with visitor group payload.
var trackData = new TrackingData<VisitorGroupTrackDataWrapper>
Payload = new VisitorGroupTrackDataWrapper
Epi = new VisitorGroupTrackingData
IncludeVisitorGroups = matchedVGs, //matched group
ExcludeVisitorGroups = unmatchedVGs //unmatched group
_trackingService.Service.TrackVisitorGroupAsync(trackData, httpContext);
private bool PageIsInViewMode()
return this._contextModeResolver.Service.CurrentMode == ContextMode.Default;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment