Can Gencer
Can Gencer

Reputation: 8885

Changing ASP.NET MVC 3 controller routing behavior

Let's say I have a few controllers with long names like VeryLongNameController.

By default ASP.NET MVC3 will map ~/VeryLongName or ~/verylongname to this controller. However I don't like the use of capital names within the URL and would like it to map all long named controllers like ~/very-long-name instead.

I know that it's possible to add custom routes one by one, but is there a way to change the default behavior?

Upvotes: 2

Views: 1263

Answers (3)

Can Gencer
Can Gencer

Reputation: 8885

I've investigated this a bit more, and got it working by making my own IHttpHandler and IRouteHandler, looking at the source for System.Web.Mvc.MvcHandler and System.Web.Mvc.MvcRouteHandler and basically copying and pasting and replacing how it resolves the controller name. However I don't like this approach at all, as it feels too heavy-weight to redo the whole request processing pipe for a simple cosmetic task. Thus, I will go with adding manual routes for each controller which has two names (which there aren't that many).

UPDATE: I've come with a much simpler solution, and that is done through overriding ControllerFactory .

public class ControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, 
        string controllerName)
    {
        requestContext.RouteData.Values["action"] =
            requestContext.RouteData.Values["action"].ToString().Replace("-", "");
        return base.CreateController(requestContext, controllerName.Replace("-",""));
    }
}

My blog post about it: http://cangencer.wordpress.com/2011/05/27/better-looking-urls-in-asp-net-mvc-3/

Upvotes: 0

Adam Tuliper
Adam Tuliper

Reputation: 30152

You can use an ActionName attribute specifically for an action method.. not a controller though


[ActionName("an-action-with-long-name")]
public ActionResult AnActionWithLongName() {
  // ...
}

Also - I prefer to add a route for every controller/action method so I don't create any unexpected mappings (I unit test them as well too) - so this is one thing to consider.

Upvotes: 0

Lazarus
Lazarus

Reputation: 43114

You can, you need to provide your own route handler implementing IRouterHandler, there's a good example here.

Upvotes: 4

Related Questions