Blog

Using a Custom RouteHandler in MVC 2

February 21, 2010

So I was trying to use a custom RouteHandler in ASP.NET MVC 2 to allow for hyphens (as opposed to CamelCase or underscores) in my urls.

I found this route handler that does the job well, but I wasn’t sure how to register the route handler. All the examples online used the Route.Add() method to add routes. However, it seems that it’s encouraged to use the MapRoute() method on the Routing collection instead, but the MapRoute() method doesn’t have a signature to provide a custom RouteHandler.

It’s a similar situation when registering routes in Areas. The RegisterArea() method adds routes using the MapRoute() method on the AreaRegistrationContext object.

It turns out that this MapRoute() method returns the Route object that is created. This object has a public RouteHandler property that can be set. This is how I am registering a custom route handler for my route:

{% codeblock lang:csharp %} public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( “RouteName”, “areaName/{controller}/{action}/{id}”, new { controller = “Home”, action = “Index”, id = "" } ).RouteHandler = new HyphenatedRouteHandler(); } {% endcodeblock %}

If anyone has a better way of doing this, please let me know.