Monday, January 18, 2010

global.asax - rewriting the URL

This is something interesting that you might want to explore in ASP.NET. The question is how to handle the following URL:

http://localhost/myWebsite/beers

Instead, there are a few ways to achieve it. The easiest way is to use the "urlMappings" in the web.config file. But, this is good for the website that does not update frequently.


  <system.web>

    <urlMappings>
      <add url="~/beers" mappedUrl="~/article_list.aspx?id=1111"/>
    </urlMappings>
  </system.web>



If you have a website that requires to publish the contents that stores in the database, then, you might wonder how to achieve the same result. So, the URL mapping feature can't meet the requirement.

Two ways to achieve this:
(1) you may create a class that inherits from IHttpModule OR
(2) add global.asax to the website and then override BeginRequest method.


Sample code


protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
// get the requested URL.
string s = this.Request.RawUrl.ToString();
// get the current website url including the virtual directory.
string current_website = (String)Application["current_website"];

if (String.IsNullOrEmpty(current_website))
{
current_website = VirtualPathUtility.ToAbsolute("~/");
Application["current_website"] = current_website;
}

// remove the virtual directory. So, only the requested file name will be in the string.
string s2 = s.Replace(current_website, "");

// if the string contains "." (ie, file extension dot)
// or "/" (ie, the folder separator), exit the checking.
if ((s2.Contains("/"))
|| (s2.Contains("."))
)
{
return;
}
else
{
// Now, we need to search for the string in the database that matches the requested url.
// If found the record, we will rewrite the url. The new URL will not reflect in the client browser.
if (s2.CompareTo("beers") == 0)
{
string url = "~/article.aspx?id=1111";
((HttpApplication)sender).Context.RewritePath(url);
}
}
}
catch (Exception ex)
{
// exception handler goes here.

}
}