views:

1406

answers:

6

How can I have lowercase, plus underscore if possible, routes in ASP.NET MVC? So that I would have /dinners/details/2 call DinnersController.Details(2) and, if possible, /dinners/more_details/2 call DinnersController.MoreDetails(2)?

All this while still using patterns like "{controller}/{action}/{id}".

+14  A: 

These two tutorials helped when I wanted to do the same thing and work well:

http://www.coderjournal.com/2008/03/force-mvc-route-url-lowercase/

http://goneale.wordpress.com/2008/12/19/lowercase-route-urls-in-aspnet-mvc/

Derek Lawless
Cheers for the mention.
GONeale
Um, the codejournal link is also the wordpress link...
Dan Atkinson
Actually the Wordpress link (@GoNeale's article) is superior. It provides extension methods for a friendlier registration, and includes handling to redirect incoming requests that aren't in lower case, so that you don't fragment your page ranking in search engines between multiple versions of the same page.
Drew Noakes
+2  A: 

This actually has two answers:

  1. You can already do this: the route engine does case-insensitive comparison. If you type a lower-case route, it will be routed to the appropriate controller and action.
  2. If you are using controls that generate route links (ActionLink, RouteLink, etc.) they will produce mixed-case links unless you override this default behavior.

You're on your own for the underscores, though...

GalacticCowboy
+2  A: 

Could you use the ActionName attribute?

 [ActionName("more_details")]
 public ActionResult MoreDetails(int? page)
 {

 }

I don't think case matters. More_Details, more_DETAILS, mOrE_DeTaILs in the URL all take you to the same Controller Action.

GuyIncognito
I haven't tried that - will it let you use either one? ("moredetails" or "more_details")
GalacticCowboy
To follow up, I tried it and it requires you to use the specified name, so no, it won't allow you to handle it either way. Also, depending how you constructed your controller action and view, you may need to specify the name of the view explicitly.
GalacticCowboy
+2  A: 

I found this at Nick Berardi’s Coder Journal, but it did not have information on how to implement the LowercaseRoute class. Hence reposting here with additional information.

First extend the Route class to LowercaseRoute

public class LowercaseRoute : Route
{
    public LowercaseRoute(string url, IRouteHandler routeHandler)
        : base(url, routeHandler) { }
    public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
        : base(url, defaults, routeHandler) { }
    public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
        : base(url, defaults, constraints, routeHandler) { }
    public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler) { }
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        VirtualPathData path = base.GetVirtualPath(requestContext, values);

        if (path != null)
            path.VirtualPath = path.VirtualPath.ToLowerInvariant();

        return path;
    }
}

Then modify the RegisterRoutes method of Global.asax.cs

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add(new LowercaseRoute("{controller}/{action}/{id}", 
        new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }), 
        new MvcRouteHandler()));

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

I would however like to know a way to use routes.MapRoute...

John Oxley
GONeale's article provides an extension method so you can write `routes.MapRouteLowercase(...` which is nicer than the above: http://goneale.wordpress.com/2008/12/19/lowercase-route-urls-in-aspnet-mvc/
Drew Noakes
+5  A: 

If you are using the UrlHelper to generate the link, you can simply specify the name of the action and controller as lowercase:

itemDelete.NavigateUrl = Url.Action("delete", "photos", new { key = item.Key });

Results in: /media/photos/delete/64 (even though my controller and action are pascal case).

Matt
+1  A: 

You can continue use the MapRoute syntax by adding this class as an extension to RouteCollection:

public static class RouteCollectionExtension
{
    public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults)
    {
        return routes.MapRouteLowerCase(name, url, defaults, null);
    }

    public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults, string constraints)
    {
        Route route = new LowercaseRoute(url, new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(defaults),
            Constraints = new RouteValueDictionary(constraints)
        };

        routes.Add(name, route);

        return route;
    }
}

Now you can use in your application's startup "MapRouteLowerCase" instead of "MapRoute":

    public void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Url shortcuts
        routes.MapRouteLowerCase("Home", "", new { controller = "Home", action = "Index" });
        routes.MapRouteLowerCase("Login", "login", new { controller = "Account", action = "Login" });
        routes.MapRouteLowerCase("Logout", "logout", new { controller = "Account", action = "Logout" });

        routes.MapRouteLowerCase(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
    }
Markus Wolters