Tip/Trick: Url Rewriting with ASP.NET

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

The most common scenarios where developers want greater flexibility with URLs are:

1) Handling cases where you want to restructure the pages within your web application, and you want to ensure that people who have bookmarked old URLs don’t break when you move pages around.  Url-rewriting enables you to transparently forward requests to the new page location without breaking browsers.

2) Improving the search relevancy of pages on your site with search engines like Google, Yahoo and Live.  Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites, which can often increase the chance of someone clicking your link.  Moving from using querystring arguments to instead use fully qualified URL’s can also in some cases increase your priority in search engine results.  Using techniques that force referring links to use the same case and URL entrypoint (for example: weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) can also avoid diluting your pagerank across multiple URLs, and increase your search results.

Approach 1: Use Request.PathInfo Parameters Instead of QueryStrings
The good news is that it is pretty simple.  Simply use the Request.PathInfo property, which will return the content immediately following the products.aspx portion of the URL.  So for the above URLs, Request.PathInfo would return “/Books”, “/DVDs”, and “/CDs” (in case you are wondering, the Request.Path property would return “/products.aspx”).
Return Request.PathInfo.Substring(1)

Approach 2: Using an HttpModule to Perform URL Rewriting
void Application_BeginRequest(object sender, EventArgs e) {

        string fullOrigionalpath Request.Url.ToString();
        
        if 
(fullOrigionalpath.Contains(“/Products/Books.aspx”)) {
            Context.RewritePath(
“/Products.aspx?Category=Books”);
        
}
        
else if (fullOrigionalpath.Contains(“/Products/DVDs.aspx”)) {
            Context.RewritePath(
“/Products.aspx?Category=DVDs”);
        
}
    }

Leave a Comment