1

I have my controller names set up as "My_Controller". I'm looking for a way to change my URL from www.mysite.com/My_Controller/My_Action to www.mysite.com/my-controller/my-action/.

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

4
  • Why can't you rename your controller ? Commented Jul 19, 2012 at 23:34
  • 1
    I don't believe dashes are allowed when naming a controller. Commented Jul 19, 2012 at 23:36
  • I hadn't heard that but then again I'd never tried ! Commented Jul 19, 2012 at 23:40
  • Well, I just tried it and it worked perfectly well. Commented Jul 20, 2012 at 0:01

1 Answer 1

4

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("-", "_");
        try
        {
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
        }
        catch { }
        return base.GetHttpHandler(requestContext);
    }
}

..and add it to your route like this:

routes.MapRoute(
            "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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the input. Let me give that a try!
For what it's worth, I just created a new Mvc3 website and specifically named the controller with an Underscore in the name and it worked just fine. Only thing being creating a controller called my_controller with an action called index yielded a url of localhost:87821/My_/index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.