Moving controllers routes into Sitecore

For a long time I have just done customer API controllers in Sitecore, the way I did them in ASP.NET MVC. By modifying the Global.ascx.cs file.


public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                "Profile",                                           // Route name
                "VisitorData",                            // URL with parameters
                new { controller = "Visitor", action = "VisitorDetailsJSON" },
                new[] { "MyCompany.Analytics.Controllers" }  // Parameter defaults
            );
        }


I am working on a project where I am going to deploy package to customer application and I do not want to overwrite their Global.ascx files. This requires me to move the routes into Sitecore and out of the Global.ascx file. Luckily, Sitecore has a pipeline for this.

First we need to write a processor that inherits the Sitecore.Mvc.Pipelines.Loader.InitializeRoutes class.


using System.Web.Mvc;
using System.Web.Routing;
using Sitecore.Pipelines;

namespace MyCompany.Analytics.Pipelines.Initialize
{
    public class InitRoutes : Sitecore.Mvc.Pipelines.Loader.InitializeRoutes
    {
        public override void Process(PipelineArgs args)
        {
            RouteTable.Routes.MapRoute(
                "Profile", // Route name
                "VisitorData", // URL with parameters
                new {controller = "Visitor", action = "VisitorDetailsJSON"},
                new[] {"MyCompany.Analytics.Controllers"});
        }
    }
}

Finally we need to add the processor to the Initialize Sitecore pipeline. While researching this, I found several ways that people approached this. I can say that what I have found is that if you don't patch the pipeline before the Sitecore.Mvc.Pipelines.Loader.InitializeRoutes processor, the Tracker.Current object becomes null. I think it breaks the API calls for the Experience Tracker.

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="MyCompany.Analytics.Pipelines.Initialize.InitRoutes, MyCompany.Analytics"
          patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']"/>
      </initialize>
      </pipelines>
  </sitecore>
</configuration>