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.

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.

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.

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.

Download Source Files