Click here to Skip to main content
Click here to Skip to main content
Go to top

ASP.NET MVC - Debugging your routes

, 16 Jun 2011
Rate this:
Please Sign up or sign in to vote.
Debugging ASP.NET MVC routes simplified using "Route Debug"
In ASP.NET MVC, we define the routes in the Global.asax.cs file. If you have noticed, it's pretty difficult to debug them as we cannot set a breakpoint to see which route is being chosen. In order to solve this, there is a useful utility out there on the internet by Phil (http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx[^]). This tip just gets you started quickly with a simple example.
 
In order to get started, the first step is to download the binary (DLL) from the following URL - http://code.haacked.com/mvc-1.0/RouteDebug-Binary.zip[^]. Extract the zip file, and then add a reference to the "RouteDebug.dll" in the extracted folder to your MVC project.
 
Then open your Global.asax file and to your Application_Start method, add the following line:
 
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
 
From this point, when you run the project, you will not see your pages' content, but you will start seeing how the routes are evaluated until a match is found.
 
To see how useful it could be, consider the following example, in this case the route debugger is not enabled. In this case, I wish to route users to their respective pages based on the user id. The URL entered would be in the format "users/{userID}". To achieve this, I add the corresponding route entries to RegisterRoutes as shown below:
 
public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute("User", "users/{userID}", new { controller = "User", action = "Index" }, new { userID = @"^[a-z]+$" });
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }
 
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
 
            RegisterRoutes(RouteTable.Routes);
        }
    }
 
"User" route attempts to achieve this. Now let's add a controller that just has an Index action which displays the user name to the user (for the sake of simplicity).
 
public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index(string userID)
        {
            ViewData["username"] = userID;
            return View();
        }
    }
 
Now, if you launch the browser with the URL, http://<your_url>/users/karthik, you will see the following:
 
http://img193.imageshack.us/img193/6493/10504233.jpg[^]
 
Everything is fine now. But if you enter http://<your_url>/users/testuser2, your application will break.
 
http://img545.imageshack.us/img545/2769/38208315.jpg[^]
 
Because, in the route "User", if you notice it expects the user id to be a string of alphabets, without numbers. But the URL entered contains numbers, causing it to break. This is a simple scenario, but, it might make us wonder what happened, if you don't remember about the regular expression constraint. In order to debug this, we could just enable the route debugger by modifying the Application_Start method as shown below:
 
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
 
            RegisterRoutes(RouteTable.Routes);
 
            RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
        }
 
Now when you launch the application with the URL http://<your_url>/users/karthik, you will see the following:
 
http://img225.imageshack.us/img225/1074/18975845.jpg[^]
 
Whereas, if you launch the application with the URL http://<your_url>/users/testuser2, the output will be:
 
http://img835.imageshack.us/img835/1561/84039760.jpg[^]
 
This clearly indicates that the intended route was not matched because the regular expression does not consider user ids with numbers in it. So change the following line in Global.asax.cs:
 
routes.MapRoute("User", "users/{userID}", new { controller = "User", action = "Index" }, new { userID = @"^[a-z]+$" });
 
with this:
 
routes.MapRoute("User", "users/{userID}", new { controller = "User", action = "Index" }, new { userID = @"^[a-z0-9]+$" });
 
Then run the application with the user id testuser2. Now you will be able to notice that the route has matched!
 
http://img146.imageshack.us/img146/9993/65743584.jpg[^]
 
This is a simple scenario, but the same tip can be helpful in a number of complex scenarios as it did for me!
 
I would like to thank Phil for this wonderful utility finally!
 
Download link - http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Karthik. A
Software Developer
United States United States
Just another passionate software developer! I recently acquired my MCTS Wink | ;)
 
My latest contribution to the open source world is a blog engine written in MVC 3 - sBlog.Net. Check it out here. For the codeproject article regarding sBlog.Net click here!
 
I have recently (re)launched my web-site. Check it out at http://thekfactor.info!

Eventually, I have a blog under my own sub-domain. It is http://blog.thekfactor.info

Also check out my latest app - directory comparer [codeproject article and dedicated site] and my latest jquery plugin - partial collapsible panel!!!


All sites were developed in ASP.Net MVC 2 Smile | :)

Follow on   Twitter

Comments and Discussions

 
GeneralThank you Pinmemberido.ran1-Nov-12 22:01 
General@supreetkaurbawa - I am not sure I am following your questio... PinmemberKarthik. A29-Jun-11 3:19 
Generalg8 but I am not much clear about technically how ur controll... Pinmembersupreetkaurbawa@gmail.com28-Jun-11 20:00 
GeneralPS - Moderators, for the images I have linked this tip/trick... PinmemberKarthik. A15-Jun-11 5:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 16 Jun 2011
Article Copyright 2011 by Karthik. A
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid