ASP.NET Permanent (301) Redirect

Within ASP.NET, the System.Web.HttpResponse class providers a method to handle HTTP redirects, aptly named Redirect. The Redirect method has two overloads:

  • Redirect (string)
  • Redirect (string, bool)

The former accepts a string representation of the URI that you’d like to redirect to. The latter accepts the string URI and a boolean indicating whether you want ASP.NET to stop processing the request immediately or to continue throughout the life cycle of the request.

Unless you’re a HTTP junkie or you’ve had a specific reason to issue a permanent redirect (reorganising a web site is a prime candidate), you can be forgiven for not realising that the Redirect method issues a temporary redirect (HTTP 302). Not having needed to issue a permanent redirect through ASP.NET before, I assumed (there is that word again) that there would be additional overloads to handle both temporary (HTTP 302) and permanent (HTTP 301) redirects or optionally another method; I was wrong.

To issue a HTTP 301 permanent redirect through ASP.NET, you need to do a little bit of manual labour; don’t worry it’s only two lines of code:

  • Response.Status = "301 Permanently Moved";
  • Response.AppendHeader ("Location", URI);

At this point, so long as nothing else interferes with the response – the client will receive a standard run of the mill 301 HTTP permanent redirect. If you know or are worried that something following the above lines may modify the response, you can issue an optional Response.End() as the third line to make it take effect immediately.

About Alistair

My name is Alistair Lattimore, I'm in my very early 30's and live on the sunny Gold Coast in Australia. I married my high school sweet heart & we've been together for longer than I can remember. Claire and I started our family in September 2008 when Hugo was born and added a gorgeous little girl named Evie in May 2010. You can find me online in the typical hangouts, Twitter, facebook & Google.
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

One Response to ASP.NET Permanent (301) Redirect

  1. Brendan says:

    Much the same thing, but the following also works:
    Response.Redirect(url, false);
    Response.StatusCode = 301;
    Response.End();

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>