ASP.net 2.0 (.net 3.5 SP1): URL Routing



In the previous post we had a quick look at the routing functionality in ASP.net 4.0. essentially means (for example) http://somehost/test.aspx?id=1 becomes http://somehost/tester/1

Routing was originally added via .net 3.5 SP1 for use with the Microsoft MVC framework, but with regards to Web Forms, Microsoft only added some real support in ASP.net 4.0.

It is however possible adding your own support for routing within ASP.net 2.0 & .net 3.5 SP1, lets have a quick look on how to achieve this.

Step 1: Add a reference to the System.Web.Routing assembly to your project.

Step 2: Make sure that you've got the required entries in your configuration file (e.g. web.config)
 
<system.web>
	<httpModules>
	...
		 <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
	</httpModules>
</system.web>
...
<system.webServer>
	<modules>
	...
		<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
	</modules>
	<handlers>
	...
		<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
	</handlers>	
</system.webServer>
...
 

Step 3: Next we're going to add some extension methods - which provides the same methods available within ASP.net 4.0.

RouteCollectionExtensions.cs
 
using System;
using System.Web.Routing;
 
public static class RouteCollectionExtensions
{
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile)
    {
        return MapPageRoute(route, routeName, routeUrl, physicalFile, null, null, null);
    }
 
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults)
    {
        return MapPageRoute(route, routeName, routeUrl, physicalFile, defaults, null, null);
    }
 
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults, RouteValueDictionary constraints)
    {
        return MapPageRoute(route, routeName, routeUrl, physicalFile, defaults, constraints, null);
    }
 
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens)
    {
        if (routeUrl == null)
        {
            throw new ArgumentNullException("routeUrl");
        }
        Route item = new Route(routeUrl, defaults, constraints, dataTokens, new RouteHandler(physicalFile));
        route.Add(routeName, item);
        return item;
    }
}
 

We also need to define a handler for handling the request.

RouteHandler.cs
 
using System.Web;
using System.Web.Routing;
using System.Web.UI;
using System.Web.Compilation;
 
public class RouteHandler : IRouteHandler
{
    private string _physicalFile;
    public RouteHandler(string physicalFile)
    {
        _physicalFile = physicalFile;
    }
 
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        HttpContext.Current.Items["RouteData"] = requestContext.RouteData;
        return BuildManager.CreateInstanceFromVirtualPath(_physicalFile, typeof(Page)) as Page;
    }
}
 

Step 4: Next we need to add the routes to the global.asax.
 
void RegisterRoutes(RouteCollection routes)
{
	routes.MapPageRoute("testroute", "tester/{id}", "~/test.aspx",
		new RouteValueDictionary { { "id", "1" } }, 		// default value
		new RouteValueDictionary { { "id", @"^\d+$" } }); 	// constraint e.g. only numerals            
}
 
void Application_Start(object sender, EventArgs e)
{
	RegisterRoutes(RouteTable.Routes);
}
 

Within the page we're routing to, we access the routing data like this:
 
public System.Web.Routing.RouteData RouteData
{
	get
	{
		return HttpContext.Current.Items["RouteData"] as System.Web.Routing.RouteData;
	}
}
 
protected void Page_Load(object sender, EventArgs e)
{
	Response.Write(RouteData.Values["id"]);
}
 








Comments



URL Routing in ASP.Net

Hi, 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.... http://mindstick.com/Articles/9992a0bc-90f5-4f04-823a-31f901b61643/?URL%20Routing%20in%20ASP.Net%203.5%28IIS7%29 Thank you very much!


Mr

Very Good Work! Thanks!


ASP Net 2.0 routing

Nice article, but where directory to put 2 class RouteCollectionExtensions.cs ,RouteHandler.cs in project (App_Code,...)?


Great!

Well done Christoff! Implemented it in 5 minutes. Thanks ever so much!


Post comment

Name *
Email
Title
Body *
Security Code
*
* Required fields

Related Posts

ASP.net 4.0: URL Routing


2010-06-01 13:22:55

Latest Posts

Be the best stalker you can be


2011-12-13 22:33:54

Syntactic sugar (C#): Enum


2011-08-04 16:50:18

Top 5 posts

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51