World is now on Opti ID! Learn more

Mark Hall
Nov 7, 2016
  1588
(0 votes)

Anonymous Project Preview

A little while ago a colleague of mine wrote an excellent post on how to create a partial route to preview specific versions of content here.  Some comments wanted to see this in the context of the projects as well as be able to allow anonymous users to be able to preview the page.  I created a small sample that addresses the issues in a different way then the partial route.

First we will create an interface for dealing with getting project identifiers and content.  In the sample we are using the host header, but you could use cookies, session, or anything else you would like to enable.  Using the url seemed most easy and less places to change the code.

using EPiServer.Core;
using System.Web;

namespace EPiServer.Reference.Commerce.Site.Infrastructure
{
    /// <summary>
    /// Helps identify project and version in the anonymous context
    /// </summary>
    public interface IPreviewProjectIdentifier
    {
        /// <summary>
        /// Gets the project version of the content, otherwsie returns the published reference.
        /// </summary>
        /// <param name="publishedContentReference"></param>
        /// <param name="httpContextBase"></param>
        /// <returns>A <see cref="ContentReference"/></returns>
        ContentReference GetProjectVersion(ContentReference publishedContentReference, HttpContextBase httpContextBase);

        /// <summary>
        /// Gets the current project id based on custom logic.  If there is no current project returns 0/
        /// </summary>
        /// <param name="httpContextBase"></param>
        /// <returns>The primary key <see cref="int"/> of the project</returns>
        int GetProjectId(HttpContextBase httpContextBase);

    }
}

Now we will create the implementation.

using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.ServiceLocation;
using EPiServer.Web.Hosting;
using System.Linq;
using System.Web;

namespace EPiServer.Reference.Commerce.Site.Infrastructure
{
    [ServiceConfiguration(Lifecycle = ServiceInstanceScope.Singleton, ServiceType = typeof(IPreviewProjectIdentifier))]
    public class DefaultPreviewProjectIdentifier : IPreviewProjectIdentifier
    {
        private readonly ProjectRepository _projectRepository;

        public DefaultPreviewProjectIdentifier(ProjectRepository projectRepository)
        {
            _projectRepository = projectRepository;
        }

        public ContentReference GetProjectVersion(ContentReference publishedReference, HttpContextBase httpContextBase)
        {
            var projectId = GetProjectId(httpContextBase);
            return projectId == 0 ? publishedReference : GetProjectReference(publishedReference, projectId);
        }

        public int GetProjectId(HttpContextBase httpContextBase)
        {
            var uri = GetUrl(httpContextBase);
            if (!uri.Host.StartsWith("project"))
            {
                return 0;
            }

            var projectId = uri.Host.Substring(uri.Host.IndexOf("-") + 1, uri.Host.IndexOf(".") - (uri.Host.IndexOf("-") + 1));
            int id;
            return int.TryParse(projectId, out id) ? id : 0;
        }

        private ContentReference GetProjectReference(ContentReference publishedReference, int projectId)
        {
            var items = _projectRepository.ListItems(projectId);
            if (items == null)
            {
                return publishedReference;
            }

            var item = items.FirstOrDefault(x => x.ContentLink.ToReferenceWithoutVersion() == publishedReference.ToReferenceWithoutVersion());
            return item == null ? publishedReference : items.FirstOrDefault(x => x.ContentLink.ID == item.ContentLink.ID).ContentLink;
        }

        private static UrlBuilder GetUrl(HttpContextBase httpContext)
        {
            UrlBuilder hostUrl;
            if (httpContext != null && httpContext.Request.Url != null)
            {
                hostUrl = new UrlBuilder(httpContext.Request.Url.AbsoluteUri)
                {
                    Path = VirtualPathUtility.AppendTrailingSlash(GenericHostingEnvironment.Instance.ApplicationVirtualPath)
                };
            }
            else
            {
                hostUrl = new UrlBuilder(VirtualPathUtility.AppendTrailingSlash(GenericHostingEnvironment.Instance.ApplicationVirtualPath));
            }
            return hostUrl;
        }
    }
}

Next we need to create a custom IFilterProvider for MVC.  We need to do this because the base class ContentController<T> has the AuthorizeContentAttribute.  This is responsible checking the access rights of the content and will prevent an anonymous user from seeing the content.

using EPiServer.ServiceLocation;
using EPiServer.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace EPiServer.Reference.Commerce.Site.Infrastructure
{
    public class ProjectFilterProvider : IFilterProvider
    {
        private readonly FilterProviderCollection _filterProviders;
        private readonly Type _authorizeContent = typeof(AuthorizeContentAttribute);
        private readonly IPreviewProjectIdentifier _previewProjectIdentifier = ServiceLocator.Current.GetInstance<IPreviewProjectIdentifier>();

        public ProjectFilterProvider(IList<IFilterProvider> filters)
        {
            _filterProviders = new FilterProviderCollection(filters);
        }

        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext,
            ActionDescriptor actionDescriptor)
        {
            var filters = _filterProviders.GetFilters(controllerContext, actionDescriptor);
            var projectId = _previewProjectIdentifier.GetProjectId(controllerContext.HttpContext);
            return projectId > 0 ? filters.Where(x => x.Instance.GetType() != _authorizeContent) : filters;
        }
    }
}

Finally we will register the filter and add a event handler to IContentRouteEvents.RoutedContent to update the content to the correct version in the context of the project.

[ModuleDependency(typeof(ServiceApi.IntegrationInitialization), typeof(EPiServer.Commerce.Initialization.InitializationModule))]
    public class SiteInitialization : IConfigurableModule
    {
        public void Initialize(InitializationEngine context)
        { 
            var providers = FilterProviders.Providers.ToList();
            FilterProviders.Providers.Clear();
            FilterProviders.Providers.Add(new ProjectFilterProvider(providers));
            
            context.Locate.Advanced.GetInstance<IContentRouteEvents>().RoutedContent += ContentRoute_RoutedContent;
            
        }

        private void ContentRoute_RoutedContent(object sender, RoutingEventArgs e)
        {
            e.RoutingSegmentContext.RoutedContentLink = ServiceLocator.Current.GetInstance<IPreviewProjectIdentifier>().GetProjectVersion(e.RoutingSegmentContext.RoutedContentLink, HttpContext.Current.ContextBaseOrNull());
        }
    }
}

Now we have a project preview for anonymous users where they can preview a live site in the context of a specific project.

http://www.screencast.com/t/FMbCw188X

Nov 07, 2016

Comments

Please login to comment.
Latest blogs
Make Global Assets Site- and Language-Aware at Indexing Time

I had a support case the other day with a question around search on global assets on a multisite. This is the result of that investigation. This co...

dada | Jun 26, 2025

The remote server returned an error: (400) Bad Request – when configuring Azure Storage for an older Optimizely CMS site

How to fix a strange issue that occurred when I moved editor-uploaded files for some old Optimizely CMS 11 solutions to Azure Storage.

Tomas Hensrud Gulla | Jun 26, 2025 |

Enable Opal AI for your Optimizely products

Learn how to enable Opal AI, and meet your infinite workforce.

Tomas Hensrud Gulla | Jun 25, 2025 |

Deploying to Optimizely Frontend Hosting: A Practical Guide

Optimizely Frontend Hosting is a cloud-based solution for deploying headless frontend applications - currently supporting only Next.js projects. It...

Szymon Uryga | Jun 25, 2025

World on Opti ID

We're excited to announce that world.optimizely.com is now integrated with Opti ID! What does this mean for you? New Users:  You can now log in wit...

Patrick Lam | Jun 22, 2025

Avoid Scandinavian Letters in File Names in Optimizely CMS

Discover how Scandinavian letters in file names can break media in Optimizely CMS—and learn a simple code fix to automatically sanitize uploads for...

Henning Sjørbotten | Jun 19, 2025 |