Simple URL Rewriting in ASP.Net with C#

If you are developing some content management site or blog, you require clean URLs for better Search engine ranking. Normally in ASP / ASP.Net we used to pass querystrings to pull the data from database.

http://example.com/load_page.aspx?Page=aboutme.aspx

But if you are using query string, it will be difficult for search engine to index. One approch to avoid this issue is creating physical files, and internally pull data from DB. It will act like a template with some information, and on the Page_Load event, it will pull the data from Database and display it in the Page. The main drawbacks of this approch are 1) it will create physical file, 2) the application may require a write permission in the WebServer for creating Files. 3) Difficult to maintain / manage. Another approch and commonly used is URL Rewriting. As the name indicates, it is rewriting an URL, a clean URL request comes to IIS, it will be mapped to another URL, which internally using Query strings. So search engines doesn’t have a problem with indexing the Pages.

http://example.com/aboutme.aspx will be mapped to automatically to http://example.com/load_page.aspx?Page=aboutme.aspx

If you are using IIS7, URL Rewriting module is available from Microsoft, and you can configure it. Here is a simple mapping mechanism which doesn’t require any configuration changes in the IIS, and works with ASP.Net 2.0 onwards.

I wrote the following code in the Global.asax file. And ASP.Net will invoke Application_BeginRequest event for every request, for ASP.Net Pages.

protected void Application_BeginRequest(object sender, EventArgs e)
{
/*
splitting the current URL, you can also do some RegEx checking instead of splitting the whole URL. And it will work only with ASPX extensions.
*/
	string[] urlParts = Context.Request.Url.AbsoluteUri.Split("/".ToCharArray());
	//Taking the Page name
	Context.RewritePath("~/Load_Page.aspx?Page=" + urlParts[urlParts.GetUpperBound(0)]);
}

And the Load_Page.aspx, Page_Load I wrote the code to read the Quey string and display the filename.

protected void Page_Load(object sender, EventArgs e)
{
    string page = Request.QueryString["Page"];
    if (string.IsNullOrEmpty(page))
    {
        Response.Write("Welcome to Home Page");
    }
    else
    {
	//Read the data from DB based on the querystring
        Response.Write("Welcome to " + page);
    }
}

As I mentioned earlier you can modify the code the Application_BeginRequest, and re-write the URL based on RegEx rules.

This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net and tagged , , , . Bookmark the permalink.

Leave a Reply

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

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>