How To Use Routing in ASP.NET 4.0
ASP.NET 4 introduces a feature called Routing to allow you to create web applications that use “clean” URLs (i.e. without the .aspx extension). Previously you would have had to use a component such as URLReWriter which was not that easy to do, especially within a shared hosting environment. Routing detaches the URL from the physical file allowing developers to design clean URLs with a straightforward hierarchy.
You may think that this is quite hard to setup but fortunately routing in ASP.NET 4 is really easy to get working and I will show you how in the following tutorial, with a complete down-loadable project you can open in Visual Studio as well. You will ideally need Visual Studio or Visual Web Developer to use the example and of course you will need to the latest version 4 of ASp.NET installed.
Step 1. Enable the Routing Handler in Your Web.Config
To allow IIS to process your requests for clean URLs, you need to tell it to use the routing handler and the routing module. To do this is very simple, two lines of code within your System.WebServer section in the web.config file.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<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 2. Setup your ASPX Pages
In this example I have a basic search form, and a seperate page to show the results. I have created seperate ASPX pages for each page I need and then have added them into a subdirectory called “Pages”. You can direct your URL to any ASPX page very easily, so for more complicated sites you can have a more elaborate file struture if you wish.
Step 3. Define your Routes
This is where the magic happens. Edit your global.asax file and in your Application_Start add your routes. Here is an example
System.Web.Routing.RouteTable.Routes.MapPageRoute("SearchPage",
"search", "~/Pages/Search.aspx");
As you can see, its very straightforward, you define a unique name for your route (the compiler will error if you try and use the same name twice) and the url you want to use for your route (in this case the url will be /search. Finally the 3rd parameter is the destination ASPX page for the route. Pretty simple! In the example project I define two routes one for the search form and one for the search results. Note that I have used the tilde sign to indicate the application root.
Step 4. Reading back the URL as parameters
So how do you use your URL to bring a parameter back into your application? For example, im my example project, you enter a keyword in a form, and it sends you to a URL like this http://localhost/search/keyword so how can you read the parameter “keyword” into your application. Firstly when you define your route, you need to tell the routing engine that your URL will contain a parameter. To do this (remember - your routes are defined in global.asax), add your route like this;
System.Web.Routing.RouteTable.Routes.MapPageRoute("SearchRoute",
"search/{searchterm}", "~/Pages/SearchResults.aspx");
As you can see the parameter is called “searchterm”. To access your parameter - Well its very easy, there is a key-value class available in ASP.NET 4 called Page.Routedata and you use it like this;
searchkeyword.Text = Page.RouteData.Values["searchterm"].ToString();
More Advanced Usage
You might occasionally need to retrive the URL of a pre-existing route. This is also very straightforward you can simply call the Page.GetRouteUrl method e.g.
Page.GetRouteUrl("SearchRoute", "keyword");
Another useful function is the Response.RedirectToRoute method, allowing you to redirect the user to a route name, instead of having to type the full Path. e.g.
Response.RedirectToRoute("SearchPage");
Also, you may be using SQLDataSource objects in your pages (personally I dont use these too often) but you can easily add your routing variables into your commands. Here is a basic example of how to do this
<selectparameters>
<asp:routeparameter name="searchkeyword" routekey=”searchterm” />
</selectparameters>
Sometimes you might want to use a wild card in your routing tables, for example to handle “all other routes” you may want to route the page to a 404.
So there you have it, ASP.NET 4.0 Routing in a nutshell. The great thing about the routing in version 4 is that the Form action URL remains clean so your postbacks are handled in the normal way. Additionally you can build more search engine friendly pages that can be easily amended at a later date if you need to. You could also data drive your routes, perhaps adding in routes from a SQL data source or XML file.