Saturday, June 5, 2010 4.0 URL rewriting aka Routing

Are you tired of having ugly urls in your website like product.aspx?product=1? Are you concerned about having a search engine optimized web site? provides the mean to easily rewrite your urls via the System.Web.Routing namespace.
I have composed a simple website with lots of comments in it, that demonstrates this new (not so new actually because this mechanism exists since .net 3.5 sp1) mechanism.

Download the source from the link below:
The main benefits of this website are:
  • User friendly urls like /product/1/My_First_Item
  • Search engine optimization (no error in the SEO Toolkit)
  • Ease on url rewrite rules
Things you should see:
During the startup of our application we define the routes. This means that whenever you change the routes, you should close the webdev server in order to reinitiate the application. In the Application_Start you will find the use of RouteTable.Routes.MapPageRoute and its overloads which provides an easy way to defines routes, while you will also find the use of the method RouteTable.Routes.Add which allows us to define our own RouteHandler.
This page demonstrates the simple use of the pages property RouteData which contains the routed data gathered by the url. Be sure to check out that we avoid rewriting the url for view1 in order to avoid any warning from the SEO toolkit (duplicate entry point of the same page, one with no arguments and /Home/1). In the aspx file you will also see the use of the new expression which gets the url by matching the used arguments to the routing rule.
In this file you will see the use of RouteTable.Routes.GetVirtualPath which returns the link to the requested resource as it’s mapped via the defined rules.
In this file you’ll find two classes. The partial class of the corresponding page and ProductRoutingHandler which implements the IRouteHandler interface in order to provide a little bit more complex logic in the Routing. This handlers loads the data of the product (based on the url’s id) and returns the loaded web page or returns a ProductNotFound.aspx web page as the result of this request…
Since you are looking in that page, check out the new MetaDescription and MetaKeywords properties of the Page which allows us to easily manipulate those head meta tags (one of the best practices in SEO).

Hope this project gives you a kick start on routing!

1 comment:

Solidus said...

Very useful post !! I'll use it in my next web application !!