Use MVC routing

Current version: 9.1

Sitecore has a default routing mechanism, but you can add custom routes in MVC-based solutions. This MSDN article describes APS.NET MVC routing in general. This topic only describe what you need to consider if you create custom routes in a Sitecore MVC solution. The description is based on using Visual Studio 2015 and Sitecore Rocks. Certain details are different in earlier versions of Visual Studio.

The safest and recommended way to add an MVC route is to add a processor in the Initialize pipeline, register the routes, and implement the route table in the RouteConfig class. This prevents you from inadvertently breaking any Sitecore routes.

To use a custom route, you must:

Define a custom route

To define a custom route:

  1. Comment out the default route in the implementation of the RouteConfig class in the RouteConfig.cs file created by Visual Studio in the App_Start folder of the solution. The code in Visual Studio looks like this:

    RequestResponse
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
  2. Add a route similar to this example:

    RequestResponse
    routes.MapRoute("product", "product/{*pathInfo}", new { scItemPath = "/{*pathInfo}"});

    This route means that an item in the root of the content tree can be accessed as /[name of product] as well as /product/[name of product].

    Sitecore provides custom values you can use when you define a route:

    • scLanguage – the context language for the request.

    • scItemPath – regardless of the route URL, the item is resolved using the value of this element.

    • scKeysToIgnore – the keys of the route URL that you want Sitecore to ignore. If they occur in the route, they are removed before attempting to resolve an item from the URL.

    You can specify a controller for a route like this:

    RequestResponse
    routes.MapRoute("product", "product/{*pathInfo}", new { scItemPath = "/{*pathInfo}", controller="Product});

If you do not specify a controller in a custom route, the default Sitecore controller handles the request. Similarly, if an action is not specified, the default action ‘Index’ is used.

The Sitecore.Mvc.Pipelines.Loader.InitializeRoutes processor of the Initialize pipeline requires a session to be present for all routes. Therefore, if you add the custom route registration processor before the Sitecore.Mvc.Pipelines.Loader.InitializeRoutes processors, the session is available in the controllers.

If you register the routes in the processor that is initialized after the Sitecore.Mvc.Pipelines.Loader.InitializeRoutesprocessor, the session is not available and the controller requests are not tracked. This is useful for custom routes that you do not need to track, for example Web API routes.

Note

Sitecore executes the httpRequestBegin pipeline to set up the Sitecore context before it transfers a request to MVC. However, Sitecore only executes httpRequestBegin when the end-point of a route has an extension listed in the parameters of the FilterUrlExtensions processor in the Sitecore.config file:

RequestResponse
<processor type="Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions, Sitecore.Kernel">
    <param desc="Allowed extensions (comma separated)">aspx, ashx, asmx</param>
    <param desc="Blocked extensions (comma separated)">*</param>
    <param desc="Blocked extensions that stream files (comma separated)">*</param>
    <param desc="Blocked extensions that do not stream files (comma separated)"></param>
</processor>

(The default setting varies somewhat between Sitecore versions). You can patch the config file and add, for example, .txt as an allowed extension:

RequestResponse
<param desc="Allowed extensions (comma separated)">aspx, ashx, asmx, txt</param>

Register the custom route

To register the custom route, you create a processor and add it to the Initialize pipeline:

  1. In your solution, create a folder called Pipelines.

  2. Right-click the folder and select Add, New Item

  3. In the Add New Item - mvc dialog, click Sitecore, Pipelines, Loader Processor.

    Add new item
  4. Visual Studio adds this content to the file:

    RequestResponse
    namespace mvc.Pipelines{
        using Sitecore.Diagnostics;
        using Sitecore.Pipelines;
        // TODO: \App_Config\include\LoadRoutes.config created automatically when creating LoadRoutes class.
        public class LoadRoutes
        {
            public void Process(PipelineArgs args)
            {
                Log.Info("Sitecore is starting", this);
            }
        }
    }
  5. In the Process method of the file, replace the code with the code that registers the routes that you created:

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    Sitecore Rocks automatically creates a patch configuration file that adds the processor to the Initialize pipeline for you:

    RequestResponse
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
      <sitecore>
        <pipelines>
          <initialize>
            <processor type="mvc.Pipelines.LoadRoutes,mvc" patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" />
          </initialize>
        </pipelines>
      </sitecore>
    </configuration>

Do you have some feedback for us?

If you have suggestions for improving this article,