Using IHttpModule to 301 redirect, Visual Basic.


A ThatsIT Solutions Tutorial

The IHttpModule is a class that intercepts requests before they hit the website; it gives you a chance to redirect before the websites knows about the request. You need to tell the web.config about the IHttpModule and the class itself sites anywhere in the website itself.

Web.Config

First here is the code for the web.config assuming the website has a namespace of PerthSeoCompany and the IHttpModule is called ReWrita.

<system.webServer>
.........
<modules runAllManagedModulesForAllRequests="true">
<add name="ReWrita" type="PerthSeoCompany.ReWrita" />
</modules>
.........
</system.webServer>

The IHttpModule Class

Next we have the code for out IHttpModule. We place our redirect logic in the Application_BeginRequest method

This code is in visual basic, don't panic we have a c-sharp version also. See Using IHttpModule, C-Sharp

Public Class ReWrita
    Implements IHttpModule

    Public Shared ReadOnly Property ModuleName() As String
        Get
            Return "ReWrita"
        End Get
    End Property

    Public Sub Init(ByVal application As HttpApplication) _
            Implements IHttpModule.Init
                AddHandler application.BeginRequest, _
                    AddressOf Me.Application_BeginRequest
                AddHandler application.EndRequest, _
                    AddressOf Me.Application_EndRequest
    End Sub

    Private Sub Application_BeginRequest(ByVal source As Object, _
             ByVal e As EventArgs)

        Dim application As HttpApplication = DirectCast(source,  _
       HttpApplication)

        Dim context As HttpContext = application.Context
        Dim fullOrigionalpath As String = LCase(context.Request.Url.ToString())
        Dim newPath As String = String.Empty

        Const www As String = "www.perthseocompany.com.au"
        Const nonWww As String = "perthseocompany.com.au"

        If context.Request.Url.Host.Equals(www) Then
            newPath = Replace(fullOrigionalpath, www, nonWww)
            context.Response.Status = "301 Moved Permanently"
            context.Response.AddHeader("Location", NewPath)
        End If

    End Sub

    Private Sub Application_EndRequest(ByVal source As Object, _
        ByVal e As EventArgs)

    End Sub

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

End Class