In this tutorial we will learn how to use URL rewriting to map URLs to different, more clean values. This comes in handy when we are working with query strings, but don’t actually want to display the query string values to the user. For instance, we could turn the URL ‘~/Default.aspx?page=Home’ into ‘~/Home’.

First, we will need to create a new ASP.NET Empty Web Site and add a new page to it named ‘Default.aspx’. For this example we will be rewriting two URL’s, a ‘Home’ page and an ‘About’ page. Let’s build our page with links to those pages. To begin, open Default.aspx and:

  1. Add a hyperlink control.
  2. Set the NavigateUrl property to ‘~/Home’.
  3. Set the Text property to ‘Home’.
  4. Add a second hyperlink control.
  5. Set the NavigateUrl property to ‘~/About’.
  6. Set the Text property to ‘About’.
  7. Add a label to the page, leaving the default values.

So now we have two different links that we will need to map. To do this we will need to enable URL mappings in our Web.Config and specify the two URL’s as follows:

This simply says that the URL of ‘~/Home’ and ‘~/About’ will be mapped to the new URL specified in the mappedUrl property. For this example these mapped URL’s link to our Default.aspx page with a query string. Next, for testing purposes, let’s display the current ‘page’ query string in our label of the page. To do this, open the Default.aspx.cs code behind file and add the following code to the Page_Load event method:

To test, load up the page. Click the home link and notice that the query string is being displayed as ‘Home’. However, notice the URL in the address bar of your browser, it looks like this ‘localhost#####/Home’. Clicking the about link will produce similar results, but for the about page. This demonstrates how easy it can be to clean up your URL’s with ASP.NET 4.0 and C#.

Download Source Files