Redirect based on Episerver visitor group

Frederik Vig 09.06.2016 12.10.34

From time to time customers ask us for the ability to redirect certain users (usually based on Episerver visitor groups) to either other pages or products in Episerver or to external URLs.

Below follows the code that we use:

    
/// 
/// Marker interface used to indicate that there is a ContentArea property for visitor criteria redirection
/// 
public interface IRedirectVisitorGroup
{
    ContentArea RedirectContentArea { get; set; }
}
public class RedirectAttribute : ActionFilterAttribute
{
    public Injected PageRouteHelper { get; set; }
    public Injected UrlResolver { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
	if (RequestSegmentContext.CurrentContextMode == ContextMode.Edit || RequestSegmentContext.CurrentContextMode == ContextMode.Preview)
	{
	    return;
	}

	var content = PageRouteHelper.Service.Content;

	// ReSharper disable once SuspiciousTypeConversion.Global
	var redirectPage = (content as IRedirectVisitorGroup)?.RedirectContentArea?.FilteredItems.Select(x => x.GetContent()).FirstOrDefault();

	if (redirectPage == null)
	{
	    return;
	}

	string url = UrlResolver.Service.GetUrl(redirectPage.ContentLink);

	if (redirectPage is PageData)
	{
	    PageShortcutType propertyLinkType = ((PageData)redirectPage).LinkType;

	    if (propertyLinkType == PageShortcutType.External)
	    {
		url = ((PageData)redirectPage).LinkURL;
	    }
	}

	filterContext.Result = new RedirectResult(url);
   }
}
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class RedirectInitialization: IInitializableModule
{
    private static bool _initialized;

    public void Initialize(InitializationEngine context)
    {
	if (_initialized)
	{
	    return;
	}

	GlobalFilters.Filters.Add(new RedirectAttribute());

	_initialized = true;
    }

    public void Uninitialize(InitializationEngine context)
    {
    }
}

There's also a NuGet package for this up on the Episerver NuGet feed.

Install-Package Geta.EPi.RedirectVisitorGroup

The only thing needed is then to implement the IRedirectVisitorGroup interface for the contnet types that should support this. Editors can then easily drag and add pages/products to the content area and personalize them using visitor groups, allowing different redirects based on different criterias.