Jonas Stawski

Everything .NET and More

Routing in ASP.NET 3.5 and 4.0

Routing was born with the creation of the MVC Framework. During the beta testing of the MVC framework people started asking for this feature to be included in so it could be used with web forms as well. The team listened and included Routing with the release of .net 3.5 SP1. Thanks for the history, but what exactly is routing?

Routing enables you to use URLs that do not map to a physical location on the server. For example in a normal page request for the default.aspx resource there has to be a physical file default.aspx on the server. On the other hand with routing you can map different URLs to a single resource. For example a normal web app might use the file Product.aspx to display product information and use the querystring as an input parameter for the Product ID resulting of a URL similar to this: Products.aspx?productID=345. The same can be accomplished with Routing, but with the difference that the URLs can be more human readable and hence more related to an action. The above example can be implemented as something like /ShowProduct/345. Search engines are not very friendly to URLs with querystring parameters and utilizing the Routing methods allows you have a more Search Engine Optimized website.

There is already a similar mechanism that accomplishes the same and it is called URL Rewriting. With URL Rewriting the incoming requests is processed and changes the URL before sending it to the actual page. If tomorrow the “fake” URL is changed the web application needs to change all URLs that utilizes it. With Routing, the URL request is not changed and there is an API that creates your URLs for a specific route. If tomorrow you decide to change the URL of a route you simply change it in one place and all your references that uses the API to create the URL are changed by default.

In order to take advantage of Routing, you have to define each route and you do so in the application_start of the global.asax:

   1: void Application_Start(object sender, EventArgs e) 
   2: {
   3:     // Code that runs on application startup
   4:     //Add the routing information for when the user clicks on a category
   5:     System.Web.Routing.Route categoryRoute = new System.Web.Routing.Route("{CategoryName}/{CategoryID}", new System.Web.Routing.PageRouteHandler("~/category.aspx"));
   6:     categoryRoute.Constraints = new System.Web.Routing.RouteValueDictionary { { "CategoryID", @"\d{1,5}" } };
   8:     System.Web.Routing.RouteTable.Routes.Add("CategoryRoute", categoryRoute);
  10:     //Add the routing information for when the user clicks on a subcategory
  11:     System.Web.Routing.Route subCategoryRoute = new System.Web.Routing.Route("{CategoryName}/{SubCategoryName}/{CategoryID}/{SubCategoryID}", new System.Web.Routing.PageRouteHandler("~/subcategory.aspx"));
  12:     subCategoryRoute.Constraints = new System.Web.Routing.RouteValueDictionary { { "CategoryID", @"\d{1,5}" }, { "SubCategoryID", @"\d{1,5}" } };
  14:     System.Web.Routing.RouteTable.Routes.Add("CategoryRoute", categoryRoute);
  16: }

in the code above we are declaring 2 routes and what we are saying is that whenever there is a request in the form of [string]/[id] to route it to the category.aspx page and whenever there is a request in the form of [string]/[string]/[id]/[id] route it to the SubCategory.aspx page. What I like to point out here is that you can specify with placeholders what each location represents and if there are any constraints. For example the first string on the first route represents the CategoryName while the second one represents the CategoryID. On line 6 we can also see that CategoryID can only be a digit of 1 - 5 characters in length and we do so with regular expresions. So if the users is trying to tamper with the URL and enters a non digit string or a 6 digit number, will not find a matching Route and display a 404 (Page Not Found) error. If you ask me that is a beautiful thing and makes your job as a developer a heck lot easier. Now you know for sure that the category id will for certain be a number and not a string and hence you don’t have to worry about possible runtime conversion errors.

This is cool, but how do I create the URLs for my routes. You do so by using the Routing API:

   1: RouteTable.Routes.GetVirtualPath(null, new RouteValueDictionary { { "CategoryName", "Suitcases" }, { "CategoryID", 1 } }).VirtualPath;

in the sample code above we see that we are using the helper method GetVirtualPath of the Routes object. We pass in a RouteValueDictionary which is a dictionary containing the name and value of each parameter. So you can see that the CategoryName is Suitcases and it’s ID is 1. This would result in the URL: /Suitcases/1 and when browsing to this URL the category.aspx page will be called. If for whatever reason you decide to change the URL from /CategoryName/CategoryID to /Category/CategoryName/CategoryID, all you have to do is change the Route definition in the Global.asax and all references that use the API call to construct the URLs will be changed automatically.

To access the values of the routes you also use the Routing API like this:

   1: Page.RouteData.Values["Category"];

which returns an object.

I hope you see how important Routing can be to your web application and start using it on your current and future projects.

Happy Programming!

Comments (1) -


I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of URL Routing in ASP.Net 3.5(IIS7) and it helped me a lot. Thanks for sharing with us. Check out this link too its also having nice post with wonderful explanation on URL Routing in ASP.Net 3.5(IIS7), for more details check this...." title="URL Routing in ASP.Net 3.5(IIS7)">URL Routing in ASP.Net 3.5(IIS7)

Thank you very much!


Add comment