Click here to Skip to main content
15,886,578 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET MVC - Debugging your routes

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
16 Jun 2011CPOL2 min read 53.4K   7   4
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)


Written By
Software Developer (Senior)
United States United States
Just another passionate software developer!

Some of the contributions to the open source world - a blog engine written in MVC 4 - sBlog.Net. Check it out here. For the codeproject article regarding sBlog.Net click here!

(Figuring out this section!)

Comments and Discussions

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

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

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