Tags: , | Posted by mason on 3/5/2009 4:02 AM | Comments (0)

Sometimes it's just the little things that make my day.  With clients inquiring more about good SEO practices, it's becoming more important to make sure all of your http redirects issue a 301 (permanent) instead of a 302 (temporary) unless your redirect truly is temporary!  In ASP.Net, if you do a Response.Redirect, the engine will emit a 302 back to the browser.  Just pop it up in Fiddler and see.  To force it to send a 301, you need to use code like this:

            response.Status = "301 Moved Permanently"
            response.AddHeader("Location", destination)
 
Wouldn't it be nice instead to do something like Response.Permanent redirect?  Sure it would, so I wrote one using 3.5 Dot Net Extensions.  Here's the code that allows me to do this:

Namespace Extensions
    Public Module Response
        <System.Runtime.CompilerServices.Extension()> _
        Public Sub PermanentRedirect(ByRef response As HttpResponse, ByVal destination As String)
            response.Status = "301 Moved Permanently"
            response.AddHeader("Location", ScrubDestination(destination))
        End Sub
        
        <System.Runtime.CompilerServices.Extension()> _
        Public Sub PermanentRedirect(ByRef response As HttpResponse, ByVal destination As String, ByVal endResponse As Boolean)
            PermanentRedirect(response, ScrubDestination(destination))
            If endResponse Then
                response.End()
            End If
            End Sub
        Private Function ScrubDestination(ByVal destination As String) As String
            Return destination.Replace("~", "")
        End Function
    End Module
End Namespace

A few rules:

1) Import System.Runtime.CompilerServices

2) Decorate each method that is an extension with System.Runtime.CompilerServices.Extension()

3) If you're writing in VB, make it a module instead of a class

To get this working in the code behind of your page just import the namespace of the class you defined the extension in (in this case Response) and you're all set.

I'm interested in hearing about any other mini customizations to the asp.net framework that makes your life easier.

To learn more about Extension methods, visit:

VB.Net, C#

Comments

Comments are closed