5,316,172 members and growing! (20,038 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate License: The Code Project Open License (CPOL)

URL Mapping / URL Rewriting / Search Engine Friendly URLs / Virtual URLs (ASP.NET)

By Manu Agrawal

URL Mapping / URL Rewriting / Search Engine Friendly URLs / Virtual URLs with postbacks in ASP.NET C# (Without hardcoding in Web.Config)
C# 2.0, C#Windows, .NET, .NET 2.0, Win2K, WinXP, Win2003, Vista, ASP.NET, VS.NET2003, VS2005, Visual Studio, Dev

Posted: 8 Apr 2007
Updated: 21 Apr 2007
Views: 40,627
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
17 votes for this Article.
Popularity: 5.15 Rating: 4.19 out of 5
0 votes, 0.0%
1
1 vote, 5.9%
2
3 votes, 17.6%
3
3 votes, 17.6%
4
10 votes, 58.8%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

(ASP.NET, C#, Visual Studio 2005)

Hi folks; Recently, I built a custom Content Management Software for a website. The client wanted the page contents to be served from database by a page ShowContents.aspx?ContentID=XX.
The main requirements were as follows:

  • Search engine friendly URLs (i.e. They would like "/finance/loan.aspx" instead of "ShowContents.aspx?ID=23").
  • Hardcoding URLs in Web.Config's URLMapping section was not an option, as there were no physical pages to map to.
  • Postback should still work on all these virtual URLs.
  • References to the images, css files, and themes should stay intact.

Solution

After a day's research, I came up with this really simple solution. I thought I should sum up the knowledge collected from various sources and make it public for everyone to benefit.
You can integrate following steps in to your existing ASP.NET project, or you can create a new one.

STEP 1

  • Create "ShowContents.aspx", that serves content based on the ContentID passed in the QueryString.
  • To enable postbacks to the raw URL in the Page_Load() event of ShowContents.aspx, insert following line Context.RewritePath(Path.GetFileName(Request.RawUrl)); // needs System.IO

STEP 2

  • Capture the URL requested by the user in the Application_BeginRequest() event of Global.asax.
  • Find the ID of the content from database that is relevant to this URL
  • ReWritePath to ShowContents.aspx?ContentID=XX. The user will see requested URL in the address bar with the desired content.
  • Any files that physically exist on the server will still get served as usual.

Using the code

// STEP 1 (ShowContents.aspx)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// This page displays contents from a database for a ContentID. This file

// must contain the following line in it's Page_Load() event.

Context.RewritePath(Path.GetFileName(Request.RawUrl)); //needs System.IO


// STEP 2 (Global.asax)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Following code goes in your Global.asax file, in the root directory of

// the project. This file captures the incoming requests' URL, gets the 

// Content ID of the content related to the URL and redirects the user to

// ShowContents.aspx?ContentID=XX. While the user still sees the requested 

// URL in the address bar.


    <%@ Import Namespace="System.IO" %>
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // If the requested file exists

        if (File.Exists(Request.PhysicalPath))
            { 
                // Do nothing here, just serve the file

            }
        // If the file does not exist then

        else if (!File.Exists(Request.PhysicalPath))
            {
            // Get the URL requested by the user

            string sRequestedURL = Request.Path.Replace(".aspx", "");
            
            // You can retrieve the ID of the content from database that is 

            // relevant to this requested URL (as per your business logic)

            int nId = 0;        
            ////// nId = GetContentIDByPath(sRequestedURL); \\\\\


           // The ShowContents.aspx page should show contents relevant to 

           // the ID that is passed here

            string sTargetURL = "~/ShowContents.aspx?ContentID=" + nId.ToString();

            // Owing to RewritePath, the user will see requested URL in the

        // address bar

            // The second argument should be false, to keep your references

        // to images, css files

            Context.RewritePath(sTargetURL, false);
        }
    }
//  That's all! :-) 

 

Hope this helps you save time on researching various sources. You might like to download the zip file containing a sample VS 2005 project.

Feedback is welcome and appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Manu Agrawal


Manu Agrawal is a .NET developer working with CTN Communications, London, UK.
He has over 7 years of professional web development experience (including 2 and half years on .NET, C#). He enjoys developing high performance and secure websites.
He holds a master's degree in E-Commerce and Management from London, UK.
Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 41 (Total in Forum: 41) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralWhy Not Use UrlRewriter.Net?membernickyt7:04 19 Jun '08  
GeneralQuestionmemberAshley van Gerven17:36 17 Jun '08  
GeneralDoesn't work!memberadalbas6:46 12 Jun '08  
GeneralURL Rewriting Advicememberatwalb7:41 11 Jun '08  
Newsimages and css not load on main pagemembershaan22:58 11 May '08  
Generalimages not workingmemberSteve45617:05 18 Mar '08  
GeneralRe: images not workingmemberManu Agrawal11:47 15 Apr '08  
GeneralExcellentmemberultradream5:20 5 Mar '08  
Generalwhy do i lose all my images and my css ?membergreekhand11:13 19 Sep '07  
AnswerRe: why do i lose all my images and my css ?memberManu Agrawal11:51 19 Sep '07  
GeneralRe: why do i lose all my images and my css ?membergreekhand12:42 19 Sep '07  
Generali tried some stuff , got another question ...membergreekhand2:28 20 Sep '07  
GeneralRe: i tried some stuff , got another question ...memberManu Agrawal3:35 22 Sep '07  
GeneralRe: i tried some stuff , got another question ...membergreekhand5:17 25 Sep '07  
GeneralDotNetNuke friendly urlsmemberTommi G16:03 16 May '07  
GeneralPOST back problemsmemberAndrei Rinea11:55 8 May '07  
NewsValidators and WebResource.axd in generalmemberAndrei Rinea6:12 3 May '07  
GeneralRe: Validators and WebResource.axd in generalmemberManu Agrawal6:57 3 May '07  
AnswerRe: Validators and WebResource.axd in generalmemberAndrei Rinea7:09 21 May '07  
GeneralVirtual DomainsmemberPaulo Moreno10:36 30 Apr '07  
AnswerRe: Virtual DomainsmemberManu Agrawal10:49 30 Apr '07  
GeneralUrl ParsingmemberTim McCurdy5:32 28 Apr '07  
GeneralHttpHandlermemberJasmine25019:42 25 Apr '07  
GeneralRe: HttpHandlermemberManu Agrawal10:33 25 Apr '07  
GeneralRe: HttpHandlermemberJasmine250111:39 25 Apr '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 21 Apr 2007
Editor:
Copyright 2007 by Manu Agrawal
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project