Understanding ASP.NET Response.Redirect

ASP.NET has a wonderful carry over from Classic ASP that many developer still use:

Response.Redirect(string url);

When ASP.NET encounters a Redirect() request it will internally throw a thread abort exception and immediately send headers back to the client (typically a browser) to go to another URL.

There are a couple of things to be aware about when you use Response.Redirect():

1. Internally a ThreadAbort exception is thrown. This is normal and if you monitor your CLR exceptions and use Response.Redirect() – you will see exceptions in the event counters.

2. Response.Redirect sets an HTTP 302 header along with the URL to be redirected to.

The SEO tip has to do with the HTTP status code that ASP.NET sends back. The 302 status code essentially says, “this item has moved temporarily”. Search engines crawling your site are not guaranteed to follow 302 redirects, nor should they. By following a 302 the search engine could incorrectly index the location of content.

However, there are cases where you do want search engines to follow the redirect because it’s a permanent redirect. In these cases you want to set an HTTP 301 header. The 301 header essentially says, “this item has moved permanently”.

Here is how:

if (send301) {

Response.AddHeader(“Location”, url);

Response.StatusCode = 301;

} else {

Response.Redirect(url);

}

Related articles:


4 Comments

  1. Instead of:

    Response.AddHeader(“Location”, url);

    Response.StatusCode = 301;

    why not:

    Response.Transfer(url);

    Just make sure you’re staying within the site and transfering to another ASP.NET page.

  2. If needed, to prevent the entire page from processing, you should consider adding Response.End like so:

    if (send301) {

    Response.AddHeader(“Location”, url);

    Response.StatusCode = 301;

    Response.End();

    }

    else

    This will obviously raise the ThreadAbort exception to prevent the rest of the page from executing.

    Another thing to consider is using IIS 6.0 wildcard redirection.

    http://www.microsoft.com/…/41c238b2-1188-4

    which also lets you specify the type of redirection using redirection flags.

    For example, you can have all requests for /a/b.aspx to be redirected to /a/c.aspx with a 301 or 302 header.

    With the IIS redirection technique, the requested aspx page never gets processed.

    Josh, you *want* the search engine to know that the resource has been moved permanently so that it modify its index accordingly. Response.Transfer wont work in cases like that.

    Raj

  3. I was thinking of the necessity of Response.End() too. What i’ve found in recent days of AJAX development is that Server.Transfer() does not work properly with Callbacks.

  4. Baijumon k p

    How can I redirect from one page in a project to a page in another project and both projects are in same solutions.