A Walkthrough to ASP.NET 4.0 URL Routing

Brij
Posted by in ASP.NET category on for Beginner level | Views : 36681 red flag
Rating: 4.67 out of 5  
 3 vote(s)

In this article, I tried to explore the new feature URL Routing of ASP.NET 4.0.


 Download source code for A Walkthrough to ASP.NET 4.0 URL Routing

Introduction:

One thing, that was always pinched me , the long URLs that I used to see in my several projects.Due to better managebility, I used to have several folders ie folder hierarchy  for maintainability of my application.But the thing that I didn't like ever that full physical path of pages in URL.There are other ways, which allow us to get rid of it like URL rewriting but that I didn't like.

Also we could have our own custom URL route handler or some third party solution, but they never been strong enough for an application.

Frankly speaking, One of my Client asked me several times , "Why this .aspx extenstion displays in URL" and also told me that he dont like this long urls. I used to tell him, this is the normal behavior of ASP.NET application.But we can change it with our own custom solution but that will require bit time and also require lot of testing.

But when Microsoft releases ASP.NET MVC2 with .Net framework SP1, and provided this Routing feature with it. I became very happy and started to explore it. In the meantime ,I thought that It should also be provided with ASP.NET, because every time you may not require to follow MVC architecture and also found that MVC has nothing special to do with URL Routing.So I was expecting and waiting for ASP.NET Webform Routing.

Now Microsoft introduced URL Routing with ASP.NET 4.0.URL routing is fully integrated, very powerfull and straight forward.

Prerequisite:

Visual Studio 2010
  

So What is URL Routing:

We access our web application using some URL that is normally the physical path of the of pages.So URL Routing is a way to provide our own URL in lieu of the physical path of the page. One other way, Routing allows us a way to configure our application to accept a requested URL which actually doesn't map to physical files. In terms of security perspective of the application, its important because one can easily know the solution structure of the application.


Why URL Routing

In 1999, an usability Jakob Nielson, writeen in his blog "URL as UI" 6 essaential points about url.These are

  • A domain name that is easy to remember and easy to spell
  • short urls
  • easy to type urls
  • URLs that visualize site structure
  • URLs that are "hackable" to allow users to move to higher levels of the information architecture by hacking off the end of the URL.
  • persistent urls that doesn't change

As from all these points, we can see the url is a part of user interface and it should be simple and easy.Urls  also made us visualize the structure of our application which might be security concern for us etc..

ASP.NET 4.0 provides us the feature, taken care all the point mentioned above.

Also these urls helps in SEO(Search engine optimastion) and improve the page hits but putting the appropriate keywords.

URL Routing Earlier

Earlier URL routing was not so easy.For that we require to have our own custom handler in a way that whenever a url is requested our custom route handler class should be invoked, and forword the request to appropriate requested page or we could have some third party solution. So lets say if we are going to develop our own custom handler then what we require to do

  1. We define the mapping in Global.asax, which maps a route pattern to route handler class.
  2. We require to develop a Route handler class which actually receives the URL, parse it,store any route parameters into some location that should be accessible to the requested page and return the instance of requested page or forward the request to the HTTPhandler that handles the requested route.
  3. Writing code in the target page in the way so that it can fetch the route parametrs and render the page accordingly.

So you can imagine that it was not a straight forward task.And also require some considerable amount of effort to develop it.

URL Rouing with ASP.NET 4.0

As a I already discussed in my introduction section, that ASP.NET 4.0 is provide us a simplified and robust way to handle ht entire URL routing mechanism.To provide URL routing, ASP.NET is now equipped with myriad classes and number of methods to provide this feature, which allows to easliy decouple the url with physical files. We just need to use them.


ASP.NET 4.0 router enables to define any kind of custom routes and we can easliy map to it to our webform page.

ASP.NET 4.0 also made our life simpler by providing us the feature "Bi- Directional routing" with the help of several componants like Route Table, Page Routehandler and ExpressionBuilders.

What is Bi-directional Routing

With the help of the Route table we cannot only decode the Routed URL with the help of Route table and with the help of other methods provided by the ASP.NET 4.0, we can also generate the URL with the ASP.NET routing mechanism, which gives us the opportunity, not to hard code the URL at several places, it will be dynamically generated with the help Routing Definition.

So we just require to change the Rout Table on any changes in the URL, and dont need to change it several other places throughout the solution.


Componeants of ASP.NET 4.0 URL Routing: 

There are two main componants of ASP.NET URL Routing.

RoutingHandler: 

Routing is basically a normal HTTPHandler, which is resposible for looking into all the incoming URL request, and look for any Routing definition is available for the URL, if yes then pass the request and data to corresponding resource.

Expression Builders: 

Expressions are provided with ASP.NET 4.0 to facilitate "Bi-Directional Routing" and more. Basically there are two types of ExpressionBuilders.

RoutURLExpressionBuilder:It is as name suggest provides the syntax which results in the value ie URL based on RouteName and Parameter according to the Rout Definitions we have.

RoutValueExpressionBuilder: As above generates the URL,RoutValueExpressionBuilder provided a syntax which recieves the value from the RouteName and Parameter from RoutedURL.

There are also few new properties like HttpRequest.RequestContext and Page.RouteData these provide facilitate to the availability of the parameters to all resorrces.

An example:

First: In this I will be displaying the image and name of the book on  my web page.

Here , I will be going to an asp.net application and will take you a step by step to create the application.

Note:

  • I have used VS2010 Beta2 version for this sample.
  • we have to use the nameswe have to use the namespace System.Web.Routing in our application to access Routing specific classes and methods.

Step 1: Define the Route in Application_Start of Global.asax. Also include namespace System.Web.Routing.

        void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.MapPageRoute("StoreRoute",
"BookStore/{Name}",
"~/Webpages/BookStore/ViewBookDemo.aspx");

}

Step 2:  (a) Now in ViewBookDemo.aspx I have four links.In First two, I have hardcoded the URL and In last I used RoutURLExpressionBuilder to generate the URL dynamically. That is known as Bi- Dirctional routing.This is the one I also liked the most, in several case we have had links in our pages those were generally hard coded.


(b) Also, I have a Label in the page and I set the the Text property dynamically with the help of Routing inforamtion as above.

Step 3: In ViewBookDemo.aspx .cs page, I have fetch the parameter from the Routing Table and set the Image1 URL dynamically in the Page_Load as below.(Include namespace System.Web.Routing)

       //fetching the parameter that is Route table
string name = Page.RouteData.Values["Name"] as string;
if (name != null)
{
if (name == "CSS")
{
Image1.ImageUrl = "~/images/css.jpg";
}
else if (name == "Django")
{
Image1.ImageUrl = "~/images/django.jpg";
}
else if (name == "IPhone")
{
Image1.ImageUrl = "~/images/iphone.jpg";
}
else if (name == "Linq")
{
Image1.ImageUrl = "~/images/Linq.jpg";
}
}

To view entire code, please download the attachment.

Now my solution hierarchy is:


And according to it my URL should be "http://localhost:2039/Webpages/BookStore/ViewBome.aspx?Name=CSS"


So here, you can see, Earlier I had use the url "http://localhost:2039/Webpages/BookStore/ViewBome.aspx?Name=CSS" but now with the help of URL Routing my URL is changed to "http://localhost:2039/Bookstore/CSS", which is the main beauty of the URL Routing.

Feedback and Suggestions: Feedback is the key for me. I would request to you all to share your feedback and give me some suggestions, which which would encourage and help in more writing. 

References:
http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx

http://haacked.com/archive/2006/11/29/Express_Yourself_With_Custom_Expression_Builders.aspx

http://sankarsan.wordpress.com/2009/08/09/asp-net-4-0-webforms-routing-part-i/

http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

Brij
Full Name: Brij Mishra
Member Level: Starter
Member Status: Member,Microsoft_MVP
Member Since: 4/9/2010 1:43:09 PM
Country: India
Cheers, Brij Microsoft MVP - ASP.NET/IIS http://brijbhushan.net
http://brijbhushan.net
Brij is a Microsoft MVP in ASP.NET/IIS. He is a very passionate dotnet programmer.He is fond learning latest microsoft technologies and love to share the knowledge to others. Visit his blog: http://brijbhushan.net Follow him on Twitter: @brij_bhushan

Login to vote for this post.

Comments or Responses

Posted by: Hemanthlaxmi on: 11/24/2011 | Points: 25
Good Article

Login to post response

Comment using Facebook(Author doesn't get notification)