ASP.NET MVC Route–If {controller} does not exist, uses a different route

Often we have a default route like the following in RouteConfig.cs:

   1: routes.MapRoute(

   2:   name: "Default",

   3:   url: "{controller}/{action}/{id}",

   4:   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

   5: );

If you don’t have anything route before and after this, then pretty much any url will match this default route.  For example, “


However, even though the route matches, the controller may not exist and a 404 error result.  In other words, “id888” is not a controller.  Let’s say id888 is {id}.

Now you can handle the missing controller error in code.  The catchall route does not really apply because this is not an unmatched route problem.


You can do something more flexible, like specifying an alternative route to use if the controller is missing.

   1: // using ICP.CustomRouting extension  MapReplaceableRoute() and AlternativeRoute

   2: // The route is replaceable in the sense that if the controller does not exist, it will use specified AlternativeRoute

   3: var defaultRoute = routes.MapReplaceableRoute(

   4:     name: "Default",

   5:     url: "{controller}/{action}/{id}",

   6:     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

   7: );



  10: // must come before the Default Map Route

  11: var shortUrlRoute = routes.MapRoute(

  12:     name: "Short Url",

  13:     url: "{id}",

  14:     defaults: new { controller = "L", action = "Index" }

  15: );


  17: // specify the alternative route to use if the matched route's controller does not exist

  18: defaultRoute.AlternativeRoute = shortUrlRoute;

In summary,

  1. Downloaded the source code project
  2. Referenced it in the web app project
  3. RouteConfig.cs: add “using ICP.CustomRouting;” and code like above.

Now my controller L action Index will handle the string “id888” argument.

Also, nuget routedebugger is a great way to troubleshoot MVC routes.


Read Siyamand’s blog post for details and code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s