Dev Explorer
Advice, tutorials and tips for beginner and experienced software/web application developers
Simple URL Rewriting in ASP.NET
Date Published: 20/05/2009 17:42Being 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.
5 Most Recent Articles
A quick guide for ASP.NET developers on how to manually trigger ASP.NET events from JavaScript.
An article for users of MySQL databases describing how they can use advanced stored procedures to improve efficiently in their applications.
A guide for LAMP developers to using stored procedures in MySQL and extending the MySQLi class.
An introduction to using the xlwt and xlrd modules for python to interact with Microsoft Excel spreadsheets.
This is an introduction to making HTTP requests from a python script/application using httplib.
Amit Habu
25/08/2009 09:26
Hello,I need a simple example using the given description.I have tried many different types of customised dll and they were successful only on local machine but not on server.Hence can u provide me the example.I need it urgently. Thank you
Amit Habu
26/08/2009 13:13
I am really thankful to Mr.Luke Skelding as they provided me a lot of help by spending their own precious time and i was successful in my work.
Rich Flood
03/09/2009 23:57
I am gettnig a runtime error in the web.config for the entry. I added the class in vb to my existing project- is this right or should I have a separate project and make a reference to this class? I am trying to implement http://lsid.speciesfile.org/urn:lsid:orthoptera.speciesfile.org:getData:12345. thanks
Srikanth
26/12/2009 15:03
I used the same code which works fine in my local system. But when I uploaded the code to my hosting server I get Could not load type 'UrlRewrite' error. Can you please help me?
Srikanth
26/12/2009 15:03
I used the same code which works fine in my local system. But when I uploaded the code to my hosting server I get Could not load type 'UrlRewrite' error. Can you please help me?
Srikanth
26/12/2009 15:03
I used the same code which works fine in my local system. But when I uploaded the code to my hosting server I get Could not load type 'UrlRewrite' error. Can you please help me?
Srikanth
26/12/2009 15:03
I used the same code which works fine in my local system. But when I uploaded the code to my hosting server I get Could not load type 'UrlRewrite' error. Can you please help me?
panchanathan
02/03/2010 09:11
your code was good... but it due to this http handlers session getting affected...
panchanathan
02/03/2010 09:11
your code was good... but it due to this http handlers session getting affected...