tech·nic·al·ly agile

IHandlerFactory

Discover how to implement a BlogRedirectHandler in ASP.NET to manage URL redirects effectively, ensuring a smooth transition for your users.

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

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 

Software Development
Comments

Related blog posts

No related videos found.

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.​

Graham & Brown Logo
Lockheed Martin Logo
Philips Logo
MacDonald Humfrey (Automation) Ltd. Logo
Genus Breeding Ltd Logo
Ericson Logo
Alignment Healthcare Logo
Boxit Document Solutions Logo
Boeing Logo
Freadom Logo
Bistech Logo
Illumina Logo
Flowmaster (a Mentor Graphics Company) Logo
Healthgrades Logo

CR2

Kongsberg Maritime Logo
YearUp.org Logo
Hubtel Ghana Logo
New Hampshire Supreme Court Logo
Washington Department of Enterprise Services Logo
Nottingham County Council Logo
Department of Work and Pensions (UK) Logo
Washington Department of Transport Logo
Royal Air Force Logo
Emerson Process Management Logo
Genus Breeding Ltd Logo
Brandes Investment Partners L.P. Logo
Flowmaster (a Mentor Graphics Company) Logo
Lockheed Martin Logo
Big Data for Humans Logo