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.

One thought on “ASP.NET Permanent (301) Redirect

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

Comments are closed.