How can I replace _ with - in my URL in ASP.NET MVC3?

I have my controller names set up as "My_Controller". I'm looking for a way to change my URL from to

Is there anyway to do this without using a URL re-writer extension? If so, how?


You can use a routehandler.

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("-", "_");
        catch { }
        return base.GetHttpHandler(requestContext);

..and add it to your route like this:

            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
        ).RouteHandler = new HyphenatedRouteHandler();

This will mean that, whenever you have a controller named "Example_Controller" with an action called "Example_Action", you will be able to call it with /example-controller/example-action

Need Your Help

Context Per Request: How to update Entity

c# .net entity-framework design-patterns domain-driven-design

I have a repository class as shown below. There is a method to get entity object – GetPaymentByID. I am retrieving a Payment object and making a change to its PaymentType property. But this is not

Using Expect to administer machines via SSH, but does not complete all tasks

linux ssh expect remote-administration

*Please do not pile on and tell me to just use SSH keys. If it bugs you that this is the way I am doing it, pretend that I am trying to telnet in instead. :-) *