Search code examples
c#asp.net-mvc-5

Why does an ASP.NET MVC route have a name?


In an ASP.NET MVC 5 web application, there is a RouteConfig class that registers many routes. In all of the examples I have seen so far, only the "Default" route has a non-empty name. The URL pattern and default route values seem to be sufficient to correctly associate any URL to the controller and action to execute. So, is there any benefit to naming a route? For debugging or logging? Just for self-documenting the code?

For example:

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

    // Most pages.
    routes.MapRoute( name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "home", action = "index", id = UrlParameter.Optional }

    // A special page.
    // Should the route have a name?
    routes.MapRoute( name: "",
      url: "special",
      defaults: new { controller = "special", action = "index", HttpVerbs = HttpVerbs.Get } );
  }
}

Solution

  • The main reason to name a route is so that if you need a link to a route from somewhere in the app, you can reference the name. That way if the actual URL/path changes you don't break everywhere in the code that references that route.