Blog Splash

Permanent Redirect Using ASP.NET

by Kerido Monday, February 22, 2010 7:49 AM

As Google recomments, when changing a website's domain name, you should add the HTTP 301 "Moved Permanently" status to the old address. To my shame, I always thought this is what HttpResponse.Redirect is about. However, using the latter produces the HTTP 302 status which is semantically somewhat different.

A trivial task that ASP.NET has no pretty code for. Here is a convenience class that does the job:

public static class HttpResponseUtility
{
  public static void PermanentRedirect(HttpResponse theResp, string theUrl)
  {
    PermanentRedirect(theResp, theUrl, true);
  }

  public static void PermanentRedirect(HttpResponse theResp,
    string theUrl, bool theEndRequest)
  {
    theResp.Redirect(theUrl, false);
    theResp.StatusCode = 301;  // as opposed to 302 set by Redirect

    if(theEndRequest)
      theResp.End();
  }
}

With this class in place, you simply call the following from a page:

HttpResponseUtility.PermanentRedirect(Response, newUrl);

Also, if you use .NET version 3.5, an extension method would do an even better job (notice the this keyword):

public static class HttpResponseUtility
{
  public static void PermanentRedirect(this HttpResponse theResp, string theUrl)
  {
    PermanentRedirect(theResp, theUrl, true);
  }

  public static void PermanentRedirect(this HttpResponse theResp,
    string theUrl, bool theEndRequest)
  {
    theResp.Redirect(theUrl, false);
    theResp.StatusCode = 301;  // as opposed to 302 set by Redirect

    if(theEndRequest)
      theResp.End();
  }
}

Your client code would then look even prettier:

Response.PermanentRedirect(newUrl);

Comments