URL Routing in ASP.NET 4.0

In the .NET
Framework 3.5 SP1
, Microsoft introduced ASP.NET Routing,
which decouples the URL of a resource from the physical file
on the web server. With ASP.NET Routing you, the developer,
define routing rules map route patterns to a class that
generates the content. For example, you might indicate that
the URL Categories/CategoryName maps to a class
that takes the CategoryName and generates HTML
that lists that category’s products in a grid. With such a
mapping, users could view products for the Beverages
category by visiting

In .NET 3.5 SP1, ASP.NET Routing was primarily designed
for ASP.NET MVC applications, although as
discussed in Using ASP.NET Routing Without
it is possible to implement ASP.NET Routing
in a Web Forms application, as well. However, implementing
ASP.NET Routing in a Web Forms
involves a bit of seemingly excessive
legwork. In a Web Forms scenario we typically want to map a
routing pattern to an actual ASP.NET page. To do so we need
to create a route handler class that is invoked when the
routing URL is requested and, in a sense, dispatches the
request to the appropriate ASP.NET page. For instance, to
map a route to a physical file, such as mapping
Categories/CategoryName to
ShowProductsByCategory.aspx – requires three
steps: (1) Define the mapping in Global.asax,
which maps a route pattern to a route handler class; (2)
Create the route handler class, which is responsible for
parsing the URL, storing any route parameters into some
location that is accessible to the target page (such as
HttpContext.Items), and returning an instance
of the target page or HTTP Handler that handles the
requested route; and (3) writing code in the target page to
grab the route parameters and use them in rendering its
content. Given how much effort it took to just read the
preceding sentence (let alone write it) you can imagine that
implementing ASP.NET Routing in a Web Forms application is
not necessarily the most straightforward task.

The good news is that ASP.NET 4.0 has greatly simplified
ASP.NET Routing for Web Form applications by adding a number
of classes and helper methods that can be used to
encapsulate the aforementioned complexity. With ASP.NET 4.0
it’s easier to define the routing rules and there’s no need
to create a custom route handling class. This article
details these enhancements. To learn more about URL Routing in ASP.NET 4.0 read on!

Further Readings

Using ASP.NET Routing Without ASP.NET MVC

URL Routing with ASP.NET 4 Web Forms

ASP.NET 4 SEO Improvements

Routing with ASP.NET Web Forms

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read