a·gen·tic a·gil·i·ty

IHandlerFactory

TL;DR; Explains how to use a custom IHttpHandler and handler factory in ASP.NET to redirect old URLs to a new site, preserving links and SEO with permanent redirects.

Published on
3 minute read
Image
https://nkdagility.com/resources/kYNSKaqUYb7
Subscribe

As you have probably noticed I have moved URL’s (sorry to all you feed readers with the duplicate entries). The reason I moved my blog was to free up the http://hinshelwood.com URL for use as a personal site that then links to my blog. When you do this you need to consider all of your current users, bookmarks, feeds, links and all that malarkey.

So, I created a WebRedirect (thanks to DynDNS.org) that means that all hinshelwood.com traffic is automatically redirected to blog.hinshelwood.com including all of the sub pages. This is fine until I actually put up a site on hinshelwood.com and brake all of the links… HttpHandler to the rescue…

The first step was to create a “BlogRedirectHandler” to redirect all of those pesky URL’s to the new site.

 1Imports System.Text.RegularExpressions
 2Imports System.Web
 3
 4Namespace Core.Handlers
 5
 6    Public Class BlogRedirectHandler
 7        Implements IHttpHandler
 8
 9        Private Shared m_Patterns() As String = {"/archive/*", _
10                                                 "/Tag/*/default.aspx", _
11                                                 "/category/*"}
12
13        Public Shared Function IsValidToRun(ByVal context As System.Web.HttpContext, _
14                                            ByVal requestType As String, _
15                                            ByVal virtualPath As String, _
16                                            ByVal path As String) As Boolean
17            For Each p In m_Patterns
18                If Regex.IsMatch(context.Request.Url.ToString, p) Then Return True
19            Next
20            Return False
21        End Function
22
23        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
24            Get
25                Return True
26            End Get
27        End Property
28
29        Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements IHttpHandler.ProcessRequest
30            Dim oldurl As String = context.Request.Url.ToString
31            If oldurl.Contains("/archive/") Then
32                Dim newurl As String = "http://blog.hinshelwood.com" & context.Request.Url.AbsolutePath
33                context.Response.StatusCode = System.Net.HttpStatusCode.MovedPermanently ' permanent HTTP 301
34                context.Response.RedirectLocation = newurl
35                context.Response.StatusDescription = "Moved Permanently"
36                context.Response.ContentType = "text/html"
37                context.Response.Write("<html><head><title>Object Moved</title></head><body>")
38                context.Response.Write("<h2>Object moved to <a href=" & newurl & " >here</a>.</h2>")
39                context.Response.Write("</body></html>")
40                context.Response.End()
41            End If
42
43        End Sub
44
45    End Class
46
47End Namespace

This little piece of code has two important pieces, the “IsValidToRun” which makes sure that we need to run it, and the “ProcessRequest” method that does the actual dog work of the redirect.

I have chosen to use a “MovedPermanently“ status so that the search engines will catch on more quickly and the new URL should quite quickly replace the old.

If we just added this handler to the web application we would loose all of our .aspx pages and only see a blank page for those that are not valid for this handler.

To handle this the easiest way is to inherit from the existing “PageHandlerFactory” that is the default in ASP.NET.

 1Imports System.Web
 2
 3Namespace Core.Handlers
 4
 5    Public Class CustomPageHandlerFactory
 6        Inherits PageHandlerFactory
 7
 8        Public Overrides Function GetHandler(ByVal context As System.Web.HttpContext, _
 9                                             ByVal requestType As String, _
10                                             ByVal virtualPath As String, _
11                                             ByVal path As String) As IHttpHandler
12            If BlogRedirectHandler.IsValidToRun(context, requestType, virtualPath, path) Then
13                Return New BlogRedirectHandler
14            Else
15                Return MyBase.GetHandler(context, requestType, virtualPath, path)
16            End If
17        End Function
18    End Class
19
20End Namespace

Then all we need to do is call our IsValidToRun method and either run the base (default) GetHandler or return our new handler…

Technorati Tags: .NET 3.5 , .NET 2.0

Smart Classifications

Each classification [Concepts, Categories, & Tags] was assigned using AI-powered semantic analysis and scored across relevance, depth, and alignment. Final decisions? Still human. Always traceable. Hover to see how it applies.

Subscribe

Connect with Martin Hinshelwood

If you've made it this far, it's worth connecting with our principal consultant and coach, Martin Hinshelwood, for a 30-minute 'ask me anything' call.

Our Happy Clients​

We partner with businesses across diverse industries, including finance, insurance, healthcare, pharmaceuticals, technology, engineering, transportation, hospitality, entertainment, legal, government, and military sectors.​

New Signature Logo

New Signature

Cognizant Microsoft Business Group (MBG) Logo

Cognizant Microsoft Business Group (MBG)

Deliotte Logo

Deliotte

Jack Links Logo

Jack Links

Xceptor - Process and Data Automation Logo

Xceptor - Process and Data Automation

Microsoft Logo

Microsoft

Kongsberg Maritime Logo

Kongsberg Maritime

Genus Breeding Ltd Logo

Genus Breeding Ltd

Illumina Logo

Illumina

Healthgrades Logo

Healthgrades

Graham & Brown Logo

Graham & Brown

Alignment Healthcare Logo

Alignment Healthcare

DFDS Logo

DFDS

YearUp.org Logo

YearUp.org

Schlumberger Logo

Schlumberger

NIT A/S

Capita Secure Information Solutions Ltd Logo

Capita Secure Information Solutions Ltd

Workday Logo

Workday

New Hampshire Supreme Court Logo

New Hampshire Supreme Court

Ghana Police Service Logo

Ghana Police Service

Nottingham County Council Logo

Nottingham County Council

Department of Work and Pensions (UK) Logo

Department of Work and Pensions (UK)

Washington Department of Enterprise Services Logo

Washington Department of Enterprise Services

Royal Air Force Logo

Royal Air Force

Cognizant Microsoft Business Group (MBG) Logo

Cognizant Microsoft Business Group (MBG)

Sage Logo

Sage

Workday Logo

Workday

Capita Secure Information Solutions Ltd Logo

Capita Secure Information Solutions Ltd

Bistech Logo

Bistech

Emerson Process Management Logo

Emerson Process Management