Sitecore 9 - MVC Routing

  • 1 min read

Introduction

Back when I started working on Sitecore (v8.2), the MVC routing would result in the following URL:

{site}/sitecore/api/{controller}/{action}

As you may know, this is not an ideal approach as it assumes that these custom routes are part of Sitecore's API but they are in fact routes for the site you're building.

With Sitecore 9; however, the best practice is to introduce a pipeline that lets you register custom MVC routes for your site. With this approach, the custom routes appear as follows:

{site}/{controller}/{action}

How it's done

1. Create route config file that maps your custom routes in MVC.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //register MVC/AJAX route(s)
        routes.MapRoute("AccountLoginRoute", "Account/Login", new { controller = "Account", action = "Login" });
        routes.MapRoute("AccountLogoutRoute", "Account/Logout", new { controller = "Account", action = "Logout" });
    }
}
2. Create a pipeline to register custom routes by inheriting InitializeRoutes pipeline.
public class RegisterCustomRoutesPipeline : InitializeRoutes
{
    public override void Process(PipelineArgs args)
    {
        //recommended way to register custom routes within Sitecore.
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
3. Finally, add an entry to your site's config transform file to initialize the processor.
<pipelines>
  <initialize>
	<processor type="MyWebsite.RegisterCustomRoutesPipeline, MyWebsite" />
  </initialize>
</pipelines>

That should do the trick!