4 Loop Web Development
  • Services
  • Information
  • Contact
  • Services
  • Information
  • Contact

ASP.NET 301 Permanent Redirect HttpHandler

Have you searched Google looking for a way to make your asp.net pages redirect ftom non www to a www page?    I did and I came up with a simple httphandler that may not be the best but seems to work.


Create a new class. I called it 301redirect.vb:

Imports Microsoft.VisualBasic
Imports System
Imports System.Web

Namespace FourLoopDev
    Public Class a301redirect
        Implements IHttpModule

        Dim _Domain As String = "yourdomain.com"

        Public Sub Dispose() Implements IHttpModule.Dispose
        End Sub

        'Tells ASP.NET that there is code to run during BeginRequest
        Public Sub Init(ByVal app As HttpApplication) Implements IHttpModule.Init
            AddHandler app.BeginRequest, AddressOf app_BeginRequest
        End Sub

        'For each incoming request, check the domain and if it starts with no 'www' then redirect it to the www version.
        Private Sub app_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
            Dim sNoWWWDomain As String = String.Format("http://{0}", _Domain)
            Dim sWWWDomain As String = String.Format("http://www.{0}", _Domain)

            Dim Request As HttpRequest = TryCast(sender, HttpApplication).Context.Request

            If HttpContext.Current.Request.Url.ToString.ToLower.Contains(sNoWWWDomain) Then
                HttpContext.Current.Response.Status = "301 Moved Permanently"
                HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace(sNoWWWDomain, sWWWDomain))
            End If

        End Sub
    End Class

End Namespace

Now open your web.config and add the following line:

        <add name="a301redirect" type="FourLoopDev.a301redirect"/>

**Notice the name is the class name and the type is the namespace plus the class name.

Save them and see what happens.