Simple URL Rewriting in ASP.NET

Date Published: 20/05/2009 17:42

Being primarily a LAMP developer I have spent many hours customising my sites' URLs using apache's excellent rewrite engine. When I moved over to .NET some time ago I presumed this to be a default feature here too but I was mistaken. To work around this problem I created a simple HTTP module which can be easily be added to projects and extended as required to simulate the behavior of Apache's rewrite engine. This article is a quick summary of that module and how to install in on your own projects. It was written in C#.NET but since it is so small I have also ported it to Visual Basic.NET for anyone who still uses VB.

What is URL Rewriting?

For those who are unsure URL rewriting is the practice of providing virtual URLs to hide or mask their real physical equivalent. This can be done for SEO, security or aesthetic reasons but overall is a nice addition to any website making urls attractive and readable (e.g "http://www.example.com/content.aspx?id=0125475&cont=twet" becomes "http://www.example.com/articles/example-article").

How it Works

It works by having a HTTP module which is called everytime the web application receives a HTTP request and transfers the server path to one designated in the code. It takes very little time to install and is very easy to customise. It is initially set up to just match requested virtual URLs in a switch case and transfer them the corresponding physical URL. This way of working is highly manual but it could easily be switched to work using URLs pulled from a database or text file depending on the content you are serving.

The HTTP Module

The HTTP module is just a class which inherits IHttpModule from the System.Web library. Create a class in your App_Code directory called "URLRewriter.cs" or "URLRewriter.vb" and put in the following code (depending on which language you are using).

C#.NET

using System;
using System.Web;

public class URLRewriter : IHttpModule
{

   public void Init(HttpApplication inst)
   {
      inst.BeginRequest += new EventHandler(OnBeginRequest);
   }

   public void OnBeginRequest(Object s, EventArgs e)
   {
      HttpApplication inst = s as HttpApplication;
      string req_path = inst.Context.Request.Path;
      string trans_path = "";
      switch (req_path.ToLower())
      {
         case "/virtual/path/to/page1":
            trans_path = "/physical/path/to/page.aspx?page=1";
            break;
         case "/virtual/path/to/page2":
            trans_path = "/physical/path/to/page.aspx?page=2";
            break;
         default:
            trans_path = "/";
            break;
      }
      inst.Context.Server.Transfer(trans_path);
   }

   public void Dispose() { }

}

Visual Basic.NET

Imports Microsoft.VisualBasic
Imports System
Imports System.Web

Public Class URLRewriter
   Implements IHttpModule

   Public Sub Init(ByVal inst As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
      AddHandler inst.BeginRequest, AddressOf Me.OnBeginRequest
   End Sub

   Public Sub OnBeginRequest(ByVal app As Object, ByVal e As EventArgs)
      Dim inst As HttpApplication = CType(app, HttpApplication)
      Dim req_path As String = inst.Context.Request.Path
      Dim trans_path As String = ""
      Select Case req_path.ToLower()
         Case "/virtual/path/to/page1"
            trans_path = "/physical/path/to/page.aspx?page=1"
         Case "/virtual/path/to/page2"
            trans_path = "/physical/path/to/page.aspx?page=2"
         Case Else
            trans_path = "/"
      End Select
      inst.Context.Server.Transfer(trans_path)
   End Sub

   Public Sub Dispose() Implements System.Web.IHttpModule.Dispose

   End Sub

End Class

The above class named URLRewriter will handle all HTTP requests made to the web application so edit the switch case in the OnBeginRequest method to meet the requirements of your own site.

Installing the HTTP Module

Now the HTTP module is in place its time to configure your web application to call it when it receives HTTP requests. This is done by adding a line to the web.config. Insert the line within the httpModules node which can be found inside the system.web node.

<system.web>
   <httpModules>
      <add name="URLRewriter" type="URLRewriter"/>
   </httpModules>
</system.web>

With that setting added to the web.config it should now be up and running. Fire up the server and give it a go, if there are any compilation problems its a good chance you've missed something so check it all over.

Conclusion

This is only a simple start to URL rewriting in ASP.NET but it can very easily be extended to better match your needs. I personally have used regular expressions similar to those used in Apache's rewrite engine as well as loading mappings from databases and XML files. If you find you have a massive switch case holding your mappings you may want to consider another system to manage your URLs. If you have any problems with the above or are encountering compilation errors feel free to comment below or use my contact me form and I'll be happy to help you out.

Comments

Sorry comments are currently disabled for maintenence

5 Most Recent Articles

Manually Triggering Events in ASP.NET from JavaScript

A quick guide for ASP.NET developers on how to manually trigger ASP.NET events from JavaScript.

Advanced Use of MySQL Stored Procedures

An article for users of MySQL databases describing how they can use advanced stored procedures to improve efficiently in their applications.

Using MySQL Stored Procedures and Extending MySQLi in PHP

A guide for LAMP developers to using stored procedures in MySQL and extending the MySQLi class.

Reading and Writing to Excel Spreadsheets in Python

An introduction to using the xlwt and xlrd modules for python to interact with Microsoft Excel spreadsheets.

Interact with the Web Using Python and the HTTP Library

This is an introduction to making HTTP requests from a python script/application using httplib.

Sponsors