EPiServer Commerce route messing with block preview

Mattias Olsson 2015-05-12 03:17:25

I started debugging by attaching to the ContentRoute.RoutedContent event and found out that the route being used when editing the block was "commerceeditpageroot". That seemed suspicious so I started looking at the routes that is registered in the EPiServer assembly and found one with the name "MediaEdit". It looks like this:

routes.MapAssetRoutes("MediaEdit", string.Concat(RouteCollectionExtensions.CmsHomePath, "MediaStaticPlaceHolder/{language}/{medianodeedit}/{partial}/{action}"), new { action = "index" }, "MediaStaticPlaceHolder", "globalassets", "siteassets");

This route seems like it should be the one being used. When I looked at the RouteCollection I noticed that the Commerce route was registered before the above and that explains our problem. I don't know if there is a better fix for this, but my solution was to move the commerce route so it was added after the "MediaEdit" route, but before the route named "editpageroot" which is registered in the EPiServer assembly. You can see the code below.

RouteConfig.cs

Helper class to register/change routes.

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        // Move commerceeditpageroot route right before editpageroot route 
        // to fix issue with block preview and languages. Why?!
        MoveCommerceEditPageRootRoute(routes);
    }

    private static void MoveCommerceEditPageRootRoute(RouteCollection routes)
    {
        var editPageRootRoutePos = GetEPiServerEditPageRootRouteIndex(routes);

        if (editPageRootRoutePos > -1)
        {
            var commerceEditPageRootRoute = GetCommerceEditPageRootRoute(routes);

            if (commerceEditPageRootRoute != null)
            {
                routes.Remove(commerceEditPageRootRoute);
                routes.Insert(editPageRootRoutePos - 1, commerceEditPageRootRoute);
            }
        }
    }

    private static int GetEPiServerEditPageRootRouteIndex(RouteCollection routes)
    {
        var editPageRootRoute = routes["editpageroot"];

        if (editPageRootRoute != null)
        {
            return routes.IndexOf(editPageRootRoute);
        }

        return -1;
    }

    private static RouteBase GetCommerceEditPageRootRoute(RouteCollection routes)
    {
        return routes["commerceeditpageroot"];
    }
}


Global.asax.cs

Make sure our code runs after EPiServer's routes have been registered.

public class Global : EPiServer.Global
{
    protected override void RegisterRoutes(RouteCollection routes)
    {
        base.RegisterRoutes(routes);
        RouteConfig.RegisterRoutes(routes);
    }
}