Published: 20 May 2011
By: Jonathan Wood
Download Sample Code

Following the lead of MVC, ASP.NET Web Forms now support URL routing. Use this technique to give your pages more user and SEO-friend URLs.

Contents [hide]

Introduction

The old web is about URLs that specify the name of the file being served along with any query arguments. For example, a page that shows information for US cities could look something like this:

This is not a very clean URL. Users without a good understanding of the web might wonder what some of those characters are for. And search engines can't easily tell which keywords are important from looking at the URL. In addition, there might even be cases where you don't really want the user to know exactly what file is being served or the tools you used to create it. (ASPX files are obviously created using ASP.NET.) A newer URL might look something like this:

This URL is much cleaner and also SEO-friendly (meaning that it is easier for search engines to index appropriate keywords for this page). And there is no indication of exactly what file is being served or what tools were used to create it.

In MVC, all URLs tend to look something like this because of the way content is served. However, as of Service Pack 1 for the Microsoft .NET Framework 3.5, you can easily implement URLs like this with ASP.NET Web Forms as well.

URL Routing

One way to think of URL routing is as a different way to specify query arguments. Of course, it works differently than query arguments, but the routing path does indeed specify arguments.

For instance, in the example URLs above, the "chicago" portion of the URL specifies the city to display. You could have a single page that displayed information for any city based on the value at this position. This value could be a primary key in a database or something else that your page can use to locate the required information.

To implement URL routing, you specify a virtual path with a number of placeholders. You can then map that virtual path to one of your physical pages. When your page is loaded, it can query ASP.NET to obtain the values in each of those placeholders.

Mapping Routes

You should map your routes when your web application starts. The easiest way to do that is by adding code to the Application_Start() handler in Global.asax as shown in Listing 1. This code calls the RegisterRoutes() method, which I created to map all my routes.

RegisterRoutes() calls RouteCollection.MapPageRoute() to register each route. The first argument is the name of the route. The value of this argument is not important unless you have code that needs to look up a route by name.

The second argument to RouteCollection.MapPageRoute() is the virtual path described earlier. Placeholders are specified using curly braces ({}). The name of the placeholder (the name between the curly braces) is the name used to identify the corresponding placeholder.

Note that a virtual path of just {id} would not work. With this virtual path, any single-level directory would map to this route. For example, www.domain.com/default.aspx, www.domain.com/states, etc. would all map to this route. Each route must have a unique virtual path or else one of the routes will get mapped to the wrong page. (Besides, I think the addition of "/Cities/" to the virtual path makes the entire path clearer, and more SEO-friendly.)

Finally, the last argument specifies the physical page that this route should be mapped to. This is the page that will be loaded when a URL matching this route is requested. This argument must begin with ~/. Note that the page doesn't need to exist in the Cities folder. In fact, normally, the Cities folder would not even exist.

You can define as many routes as you need to.

Listing 1: Registering Routes in Global.asax

Handling a Routed Request

The next step is to implement the page that handles the routed request. In this case, City.aspx. Listing 2 shows this page's Load event handler.

If this is not a postback, the code starts by obtaining the value in the id placeholder. It does this by querying the RouteData.Values collection. Note that you should include some reasonable error handling with this code. It is possible for the user to request the page directly, in which case there would be no routing data.

If the id value is found, the code then attempts to lookup the data that corresponds to the value. In this case, it looks it up in a List collection. A more common scenario would be one where the code looks the value up in a database.

Finally, if the item is found, the corresponding data is displayed in the page. Otherwise, a message that states the City is not available is displayed. Alternatively, you could redirect the user to your home page or an error page if the placeholder data was missing or invalid.

Listing 2: City.aspx

The result is a Web Form that works much like any other Web Form, except it has a virtual URL as shown in Figure 1.

Figure 1: A Web Form with a Virtual URL

A Web Form with a Virtual URL

Summary

And that's really all there is to it. Of course, you'll need to ensure any links to your routed pages use the virtual path. Ideally, your users will never see a link to the physical page that handles routed URLs.

The attached download contains the full project described in this article. It's a simple website that uses URL routing to display information for any of several cities.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Jonathan Wood

Jonathan developers software and websites from home in the Salt Lake City, UT area. He hikes each week with his German Shepherd Dog, Suki.

This author has published 2 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.

You might also be interested in the following related blog posts


ASP.NET 4 Beta 2 - New Version, New Docs, New MSDN Site ! read more
Announcing Microsoft Ajax Library (Preview 6) and the Microsoft Ajax Minifier read more
URL Routing with ASP.NET 4 Web Forms (VS 2010 and .NET 4.0 Series) read more
Announcing the WebsiteSpark Program read more
Accessing Images On Flickr From An ASP.NET Website Using The Flickr.Net Library read more
Announcing the Microsoft AJAX CDN read more
Intersoft Solutions Announces WebUI Studio 2009 Service Pack 1 read more
Clean Web.Config Files (VS 2010 and .NET 4.0 Series) read more
WebResource access in ASP.NET MVC read more
Url.Action() and RouteValue Encoding read more
Top
 
 
 

Please login to rate or to leave a comment.