We access our webapplication using some URL that is normally the physical path of the 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. From the security perspective of the application, it's important because one can easily know the solution structure of the application.
URL Routing with ASP.NET 4.0
ASP.NET 4.0 provides us a simplified and robust way to handle the entire URL routing mechanism. To provide URL routing, ASP.NET is now equipped with myriad classes and a number of methods to provide this feature, which allows to easily decouple the URL with physical files. We just need to use them.
Components of ASP.NET 4.0 URL Routing
This is basically a normal HTTPHandler, which is responsible for looking into all the incoming URL requests, and looking for any Routing definition available for the URL, if yes, then pass the request and data to the corresponding resource.
Expressions are provided with ASP.NET 4.0 to facilitate Bi-Directional Routing and more. Basically there are two types of ExpressionBuilders.
As the name suggests, it provides the syntax which results in the value, i.e., URL based on RouteName and Parameter according to the Route definitions we have.
As above, it generates the URL, RouteValueExpressionBuilder provides a syntax which receives the value from the RouteName and Parameter from RoutedURL.
There are also a few new properties HttpRequest.RequestContext and Page.RouteData which facilitate the availability of the parameters to all resources.
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
1. Now in ViewBookDemo.aspx, I have four links. In the first two, I have hardcoded the URL and in the last, I used RoutURLExpressionBuilder to generate the URL dynamically. That is known as Bi- Directional routing. This is the one I also liked the most, in several cases, we have had links in our pages that were generally hard coded.
2. I also have a Label in the page and I set the Text property dynamically with the help of Routing information as above.
Here, I fetch the parameter from the Routing Table and set the Image1 URL dynamically.(Include namespace System.Web.Routing):
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";
according to it, my URL should be http://localhost:2039/Webpages/BookStore/ViewBome.aspx?Name=CSS as: