ASP.NET Redirect

ASP.NET web programming framework

Your ASP.NET website received a request for a page and you want to temporarily redirect to another location. With the Redirect method, you can issue a response that causes the browser to immediately go to another page.

This C# tutorial uses the Redirect method in ASP.NET. This method redirects requests.

Example

First, we acquire the Response object from the base class. Then, we invoke the Redirect method, with a complete URI string specified as the first argument. The second argument to Redirect is the boolean literal false, which indicates we do not want an exception to be thrown to terminate the page. If you do not pass false, an exception will occur and this can slow down websites and complicate error handling.

Example that uses Redirect [C#; ASP.NET]

using System;
using System.Web.UI;

namespace WebApplication6
{
    public partial class List : Page
    {
	protected void Page_Load(object sender, EventArgs e)
	{
	    // Get response.
	    var response = base.Response;
	    // Redirect temporarily.
	    // ... Don't throw an HttpException to terminate.
	    response.Redirect("http://www.dotnetperls.com/list", false);
	}
    }
}

Result of the page

HTTP/1.1 302 Found
Content-Type: text/html; charset=utf-8
Location: http://www.dotnetperls.com/list
Server: Microsoft-IIS/7.0
Date: Fri, 13 Aug 2010 21:18:34 GMT
Content-Length: 144

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="http://www.dotnetperls.com/list">here</a>.</h2>
</body></html>

Result of the page. You can see that the webpage, when accessed, simply returns a HTTP 302 Found header. The location is set to the first argument of the Redirect call. The body of the response contains an HTML page, which won't typically be rendered by browsers.

SEO issue

Warning

When you call Redirect, browsers and search engine spiders alike will be directed to the new page. However, search engines like Google will not immediately update their indexes to point to the new page. They will instead keep the old page URL, and this will cause all visitors to be redirected each time. It is better to call RedirectPermanent to change the URL in a search engine.

Response RedirectPermanent Method

Summary

In my experience the Redirect method is less useful than the RedirectPermanent method. It will cause search engine results to be less current, and this can also impact performance because visitors will not be accessing the best URL. Redirect may be most useful for login pages or more complex situations where search engines are not the focus.

ASP.NET Tutorials
.NET