Tuesday, 26 July 2011

Rewriting a URL on-the-fly using ASP.NET 2.0 and C#.NET


This tutorial shows you how to rewrite URL paths on-the-fly using ASP.NET 2.0 and C# .NET.

In some instances you may want to rewrite a URL on-the-fly in ASP.NET. This is done in the Global.asax file which contains event handlers for major events like Application_Start and Session_Start. This file is located in the root of the application directory and handles application level logic that doesnt interact with or create UI objects. In this example, we will be writing code for the Application_BeginRequest to rewrite the URL before any resource or URL is activated in the application.

To perform any kind of advanced URL rewriting you will need to use the RegularExpression class objects found in System.Text.RegularExpressions.

Whenever a new HTTP request starts the Application_BeginRequest() event fires and we grab the current request in a HTTPContext object.

HttpContext myContext = HttpContext.Current;

Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we've found so far.

By accessing the Request property of this object we can study an HttpRequest object and determine information commonly included in most HTTP requests (such as the URL requested). In this example, we want to redirect any request for "Default.aspx" and rewrite it to "Something.aspx". We start by creating a Regex object that will capture the appropriate text.

Regex rewrite_regex = new Regex(@"(.+)\/((.+)\.aspx)", RegexOptions.IgnoreCase);

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!

This regular expression has three capturing groups: the directory the file is in, the filename (without extension), and the filename (with extension). We test the last group (filename w/ extension) to make sure it matches "Default.aspx" before we use the RewritePath() function of our HttpRequest object and forward the user before any page has been loaded.

try
{
//see if we need to rewrite the URL
Match match_rewrite = rewrite_regex.Match(myContext.Request.Path.ToString());

if (match_rewrite.Groups[2].Captures[0].ToString() == "Default.aspx")
{

myContext.RewritePath("Something.aspx", true);
}

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!

The flow for the entire Global.asax page is as follows. Some event stubs are created by default when adding a new Global.asax file via Visual Studios. These are included for completeness.

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup

}

void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown

}

void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started

}

void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

}

protected void Application_BeginRequest(object sender, EventArgs e)
{

HttpContext myContext = HttpContext.Current;

Regex rewrite_regex = new Regex(@"(.+)\/((.+)\.aspx)", RegexOptions.IgnoreCase);

try
{

//see if we need to rewrite the URL
Match match_rewrite = rewrite_regex.Match(myContext.Request.Path.ToString());

if (match_rewrite.Groups[2].Captures[0].ToString() == "Default.aspx")
{

myContext.RewritePath("Something.aspx", true);

}
} catch (Exception ex) { }
}
</script>

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment