Tuesday 6 March 2012

URL Rewriting in .Net || How URL Rewriting works || HTTP Module in .NET || installing the HTTP Module



What is URL Rewriting?
Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7.
http://www.roja-dotnet.com/show_a_product.aspx?product_id=7

The problems with this kind of URL structure are that the URL is not at all memorable. It's difficult to read out over the phone (you'd be surprised how many people pass URLs this way). Search engines and users alike get no useful information about the content of a page from that URL. You can't tell from that URL that that page allows you to buy a Norwegian Blue Parrot (lovely plumage). It's a fairly standard URL - the sort you'd get by default from most CMSes. Compare that to this URL:
http://www.roja-dotnet.com/products/7/

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 every time 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 it’s 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.

No comments:

Post a Comment