Archive

Posts Tagged ‘.NET’

How to: Allow hyphens in URL’s using ASP.NET MVC 2

February 6th, 2010

If you wan’t to allow hyphens in your URL’s you will need to change the way the routing works in your Global.asax file.

First create a new class which extends the MvcRouteHandler and place this in the Global.asax file after the main MvcApplication class.

C#:

public class HyphenatedRouteHandler : MvcRouteHandler{
	protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
	{
		requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
		requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
		return base.GetHttpHandler(requestContext);
	}
}

VB:

Public Class HyphenatedRouteHandler
    Inherits MvcRouteHandler
 
    Protected Overrides Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler
        requestContext.RouteData.Values("controller") = requestContext.RouteData.Values("controller").ToString.Replace("-", "_")
        requestContext.RouteData.Values("action") = requestContext.RouteData.Values("action").ToString.Replace("-", "_")
        Return MyBase.GetHttpHandler(requestContext)
    End Function
 
End Class

Then you need to replace the routes.MapRoute with an equivalent routes.Add specifying the new handler as the MapRoute does not allow you to specify a custom route handler.

C#:

routes.Add(
	new Route("{controller}/{action}/{id}", 
		new RouteValueDictionary(
			new { controller = "Default", action = "Index", id = "" }),
			new HyphenatedRouteHandler())
);

VB:

routes.Add(New Route("{controller}/{action}/{id}", 
	New RouteValueDictionary(New With {.controller = "Home", .action = "Index", .id = ""}), 
		New HyphenatedRouteHandler()))

I hope this is useful, any questions feel free to get in touch.

Would like to say thanks to John from here for answering the original question on Stackoverflow

Author: Zero7Web Categories: .NET Tags: , , , , ,