URL Rewriting With ASP.NET and C hash


In this article we will learn how to use URL rewriting to map URLs for better search results and user friendly URLs. 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=Books’ into ‘~/Books’.

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 ‘Books’ page and an ‘Magazine’ page.

Let’s build our page with links to those pages. To begin, open Default.aspx and:

  • Add a hyperlink control ans set the text  property to Books.
  • Set the NavigateUrl property to ‘~/Books
  • Add a second hyperlink control and set the text property to Magazine.
  • Set the NavigateUrl property to ‘~/Magazine’.

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:

It simply says that the URL of ‘~/Books’ and ‘~/Magazine’ 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:

LblMsg.Text = Request.QueryString[“page”];

To test, load the page in the browser and  click on the Books link and notice that the query string is being displayed as ‘Books’. However, notice the URL in the address bar of your browser, it looks like this ‘localhost#####/Books’. Clicking the Magazine link will produce similar results, but for the Magazine page. This demonstrates how easy it is to use URL’s rewriting with ASP.NET 4.0 and C#.

Rate This
[Total: 0    Average: 0/5]

Leave a comment

Your email address will not be published. Required fields are marked *

*