Custom Routing in Sitecore

Rainfall Software
Rainfall Software
Published in
2 min readOct 31, 2022

Here’s another post that’s just as much for my future self as for everyone else. Occasionally it becomes necessary to create a page or endpoint outside of Sitecore’s URL mapping system. There’s a variety of reasons to do this, but in this case I needed to create an endpoint that would be called by Javascript on the front end.

Photo by Pablo García Saldaña on Unsplash

The Controller

The first think we’ll need is a controller to expose the endpoint that our front-end script will communicate with. There are infinite variations of what this controller could look like, but a minimalist example would be:

public class MyApiController : ApiController
{
public override string MyEndPoint()
{
return "Hello World!";
}
}

Note that the controller extends ApiController, not the base Controller class like most do.

Registering Routes

Next, we need to set up a class that will define our custom routing:

public class RegisterRoutes
{
public virtual void Process(PipelineArgs args)
{
RegisterRoute(RouteTable.Routes);
}
protected virtual void RegisterRoute(RouteCollection routes)
{
RouteTable.Routes.MapHttpRoute("my-endpoint",
"hello/world",
new { controller = "MyApi", action = "MyEndPoint" }
);
}
}

A couple key points to note here:

  1. The “my-endpoint” name does not effect the functionality at all, it’s just a unique name for this custom route.
  2. The endpoint will be available at the URL: http://mysite.com/hello/world
  3. Note that the controller is set to “MyApi”, the “Controller” part of the class name is left out.

Configuration

Finally, we need a line of configuration so that Sitecore runs our RegisterRoutes class and sets things up.

<sitecore>
<pipelines>
<initialize>
<processor type="MyProject.RegisterRoutes, MyProject"
patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']" />
</initialize>
</pipelines>
</sitecore>

Once all this is deployed, our custom endpoint should be accessible to the front-end code.

--

--