URL Routing with ASP.NET 4.0
Published: 08 Sep 2009
Unedited - Community Contributed
One of the features of ASP.NET 4.0 is built-in support for bi-directional URL routing. In this article, Rohit examines some of the new features available with the use of Visual Studio 2010 Beta 1 more details with some hands-on work and shows the URL routing with the .NET Framework 4 Beta 1. This covers the benefits of URL routing and changes with ASP.NET 4.0. Mainly we will be seeing how ASP.NET 4.0 makes things easier by implementing bi-directional routing with the help of components like the RouteTable, PageRouteHandler and ExpressionBuilders. This allows ASP.NET 4.0 users to easily decouple URLs from physical files.
by Rohit Sinha
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 26705/ 46


Editor's Note: This was written in August 2009. Changes to ASP.NET 4.0 are expected that will impact the validity of some of the findings in this article in the future.

One of the features of ASP.NET 4.0 is built-in support for Bi-directional URL Routing. With VS 2010 Beta 1 out for sometime, I dig into more details with some hands-on work. In this article I will show the implementation of URL routing with .NET framework 4 Beta 1. It will also cover benefits of URL routing and changes with ASP.NET 4.0. Mainly we will be seeing how ASP.NET 4.0 makes things easier by implementing bi-directional routing with the help of components like RouteTable, PageRouteHandler and ExpressionBuilders. This allows ASP.NET 4.0 users to easily decouple URLs from physical files.

Why URL Routing

URL is now considered as a part of User Interface (UI) and needs proper attention. Some of the advantages are:

·         Help in SEO (Search Engine Optimization) and hence improve page hits by putting relevant keywords in the URL.

·         Users are becoming more tech savvy and find directly manipulating the URL easier than inputting text boxes and clicking buttons.

·         Short and easy to type URLs are good.

·         URLs are persistent i.e. users do not want to rely on your page names and folder structure when application is accessed. For e.g. if a user bookmarks a page and for some reasons developer need to restructure the code files. User might not get to the same page through the same bookmark.

ASP.NET 4.0 & URL Routing

Initially URL Routing was introduced with ASP.NET MVC. It was a great start but cleaner version was launched with ASP.NET 3.5 SP1 where System.Web.Routing assembly (originally part of ASP.NET MVC) introduced. However here you were needed to create your own IRouteHandler and implement GetHTTPHandler method.

ASP.NET 4.0 is definitely going to take us much ahead with built-in support for URL routing. Here you got all necessary components to enable routing in much easier way. Now no need of implementing IRouteHandler, ASP.NET 4.0 already provided a readymade PageRouteHandler class which picks the appropriate PageHandler to service the request and provides properties and methods for defining URL mapping to a physical file. It has got ExpressionBuilders for bi-directional support.

Let’s drill down further with an example. We will prepare a web application where a user can see Contact details (name and age) based on selected State i.e. the URL will have a URL pattern like - /State/{State Came}. This will list all the contacts for specified state name. For CA the URL should be - http://localhost:4951/State/CA , where State is the key and CA is the value. User can further go ahead and directly change the URL (CA to NY) and see desired results.

Let’s proceed step by step:

·         I have shown below a snapshot of the database table which this application will be using for Contacts:

·         Open VS 2010 solution and select ASP.NET Web Application

·         Add Global.asax to current web application:

·         Create a new route by adding route to a RouteTable. RouteTable stores different routes (URL patterns) which are used for processing the requests to construct URLs dynamically. We want to add routes to RouteTable on start of the application.  We need to pass the instance of PageRouteHandler to the Route constructor and map URL to physical file. PageRouteHandler is the class under System.Web.Routing which defines how URL maps to a physical file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
namespace URLRouting
    public class Global : System.Web.HttpApplication
        protected void Application_Start(object sender, EventArgs e)
            RouteTable.Routes.Add("State"new Route("State/{Name}", 
              new PageRouteHandler("~/Default.aspx")));

·         Now we have defined that any URL with pattern like “State/{Name}” will be handled by Default.aspx where {Name} is a placeholder for state name. We will use Default.aspx and handle the incoming request with ExpressionBuilders:

·         Above picture shows how bi-directional routing is implemented. Hyperlinks are generated on the fly. Let’s explore this in more detail.

·         RouteUrl is an expression builder which builds the correct URL on the dynamically based on supplied parameters. So you do not to hardcode the URL e.g.

<asp:HyperLink ID="HyperLink1" runat="server" 
    NavigateUrl="<%$RouteUrl:RouteName=State, Name=TX%>"  Text="Texas" />

This will actually evaluate to following URL based on defined route under RouteTable:

<asp:HyperLink ID="HyperLink1" runat="server" 
    NavigateUrl=http://localhost:4951/State/TX  Text="Texas" />

·         We need Hyperlinks for different states (TX, CA and NY) and URL to be evaluated with ExpressionBuilders:

<asp:Label ID="Label2" runat="server"  text="Select State : " ></asp:Label>    
         <asp:HyperLink ID="HyperLinkTX" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=State, Name=TX%>"  Text="Texas" />
         <asp:HyperLink ID="HyperLinkCA" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=State, Name=CA%>"  Text="California" />
         <asp:HyperLink ID="HyperLinkNY" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=State, Name=NY%>"  Text="NewYork" />

·         We need to show the selected State as “List of Contacts from: <state code>. State Code (TX, CA or NY) are stored as value of the route parameter. There are different ways to get the value.  You can use the Route object

1.    RouteData.Values["name"];

2.    Use an expression builder:

<%$ RouteValue:name %>

·         We will use expression builder <%$ RouteValue:name %>

        <asp:Label ID="Label1" runat="server"  Font-Bold=true 
          text="List of Contacts from : " ></asp:Label>    
        <asp:Label ID="lblRouteData" runat="server" Font-Bold=true 
          text="<%$RouteValue:Name%>" ></asp:Label>

·         Now create a sqldatasource, assign connection string and use RouteParameter to pass parameters. RouteParameter basically binds the value of URL to a parameter object. Its Routekey property will be used to retrieve the value of a placeholder. You can also put DefaultValue if you need.

<asp:sqldatasource id="SqlDataSource1" runat="server"  
   connectionstring="<%$ ConnectionStrings:MyConnection %>"
   selectcommand="SELECT Name, Age FROM ContactInfo where State=@StateCode">
       <asp:routeparameter name="StateCode" RouteKey="Name"  />

·         As shown above, we will query a table ContactInfo with StateCode is passed to retrieve the details of a specific state.

·         We will show the results in following DataList control:

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
        <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
        <br />
        <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />        <br /><br />

·         Off course there will be a Connection String (“MyConnection”) in Web.Config:

<add name="MyConnection" connectionString="Data Source=LENOVO-F4A0E849\MSSMLBIZ;
Initial Catalog=Test;Integrated Security=True" />

·         Finally this is how output web page will be shown:

·         User selects Texas by clicking the hyperlink. It will redirect to /State/TX, this pattern in turn mapped to Default.aspx (earlier defined in the RouteTable).

·         See below the status bar showing generated URL when you move your mouse over to Texas. This is generated through ExpressionBuilder.

·         Now user selects NY, this is how it shows the details of contacts under selected state.


The new ASP.NET 4.0 URL routing players like PageRouteHandler, Expression builders and RouteParameter shows how we can easily we can implement routing with bi-directional support. This eventually helps in building applications with meaningful, short and friendly URLs.

I am eagerly waiting for 2010 release.

Happy Coding!!






User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2023 ASPAlliance.com  |  Page Processed at 2023-09-27 7:13:44 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search