Friday, October 21, 2016

Register Custom MVC routing in Sitecore

Defining custom routes in the Global.asax file, causing conflicts with a number of default routes defined by Sitecore.

Note: Below way does not conflict with the default Sitecore routes.

Step 1:

Create a custom processor for the initialize pipeline and define custom route in the Process method similar to the following:

public class RegisterCustomRoute
{
  public virtual void Process(PipelineArgs args)
  {
    
    RouteTable.Routes.MapRoute(
                "CustomRoute",                                              // Route name
                "some/route/{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "controllername /", action = "action name", id = UrlParameter.Optional }  // Parameter defaults
  }
}

Step2:

Add this processor to the initialize pipeline right before the Sitecore InitializeRoutes processor. You can do this with the help of the configuration patch file in the following way:

Create CustomRouteConfiguration.confi as below:

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

Step3 :

Place the patch file into a subfolder of the /App_Config/Include directory.

Happy coding!

2 comments: