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

June 6, 2010 by C#   ASP.NET  

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"]);
}


Leave a Comment


Obvious October 13, 2014 by Christoff Truter

Hi Azami. Obviously I didn't post the whole web.config (hence the ... in my samples), I only posted the relevant parts that generally needs to be added.What your application requires/needs above that is up to you.

Session State October 3, 2014 by Azami

Well done! but when I use this pattern the target physical page lost the session state and I see this error : Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

Not WORKING on Production server June 9, 2014 by Anonymous

Everything is working fine on local server but when uploaded on production server.....its not working any idea why this thing is happening ?

Re: MapPageRoute missing February 20, 2014 by Christoff Truter

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

Getting Error January 21, 2014 by Ajit Sswain

void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("testroute", "tester/", "~/test.aspx", new RouteValueDictionary }, // default value new RouteValueDictionary }); // constraint e.g. only numerals } MapPageRoute is not there in .net 3.5 How to solve it. please any idea?

Really Helpfull February 13, 2013 by jugal

very easy to implement very cutomized code... very very thank full to provide this code... Heartly thank full to cstruter.com

URL Routing in ASP.Net January 10, 2012 by JayPrakash Sharma

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 July 14, 2011 by Stuck

Very Good Work! Thanks!

ASP Net 2.0 routing November 21, 2010 by Anonymous

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

Great! September 15, 2010 by Mau

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