(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.
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.
- 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
- 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
<%@ Import Namespace="System.IO" %>
protected void Application_BeginRequest(object sender, EventArgs e)
else if (!File.Exists(Request.PhysicalPath))
string sRequestedURL = Request.Path.Replace(".aspx", "");
int nId = 0;
string sTargetURL = "~/ShowContents.aspx?ContentID=" + nId.ToString();
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.