.::  Using a HTTP 301 Redirect in ASP.NET and C# (CSharp)  ::.

Implementing a 301 Moved Permanently redirect when globally changing a website’s host address is crucial for most search engines to spider and rank a website correctly.

Situation:
.Text WebLog removes the www. from the host address when producing links through out the application. For instance, if the user is viewing www.jaydouglas.com/blog/default.aspx .Text produces links such as jaydouglas.com/blog/somepage.aspx … As you see this method removes the www. from the web address. This functionality was giving my blog a Page Rank of 0 from Google. Looking through the search results that Google produces for my website, I noticed that all pages that Google was indexing (excluding the Blog) displayed the host address of www.jaydouglas.com. After some research I decided to make the whole www.jaydouglas.com website remove the www. from the host address using a 301 redirect.

Underlying Technology:
ASP.Net, C#

The Code:
JayDouglas.com utilizes a base class that inherits for System.Web.UI.Page for most .ASPX code behind files. Using a base class allows for global changes to the graphical template of the site and shared code functionality. I decided to place the code to parse the Url and redirect if necessary in a overridden OnInit method.
protected override void OnInit(EventArgs e)
{
    int i = Request.Url.ToString().IndexOf("www.");
    if (i < 8 && i != -1)
    {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", Request.Url.ToString().Remove(i, 4));
        Response.End();
    }
    base.OnInit (e);
}

Home  |   Articles  |   Resume  |   Contact Jay  |   Blog
Site designed and developed by Jay Douglas
© 2001 – 2008
Thursday, August 21, 2008