Response.Redirect and Response.RedirectPermanent Methods in ASP.NET

While developing web applications there are certain situations when you need to redirect from one page to another. Redirecting simply means a way of hopping on from one page to another. In ASP.NET there are two methods for this purpose.

These are:

  1. Response.Redirect and
  2. Response.RedirectPermanent.

In this article, we will study these two methods in detail but before that let’s see how MSDN defines these two methods.

How MDSN Defines Redirect and RedirectPermanent:

Response.Redirect asp.net

Response.Redirect:

Response.Redirect method, “Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate”.

Response.Redirect Syntax:

This method has two overloads:

  1. Redirect(url)
  2. Response.Redirect(url, endResponse)

Where,

url is the target url where you wish to redirect the client.

endResponse is a Boolean flag which indicates whether execution of the current page should terminate or not. The default is true.

Response.RedirectPermanent:

Response.RedirectPermanent method, “Performs a permanent redirection from a requested URL to a specified URL”.

Response.RedirectPermanent Syntax:

This method has two overloads:

  1. Response.RedirectPermanent(url)
  2. Response.RedirectPermanent(url, endResponse)

Where,

url is the target url where you wish to redirect the client.

endResponse is a Boolean flag which indicates whether execution of the current page should terminate or not. The default is false.

Difference between ‘endResponse’ True/False:

When you use Response.Redirect(url, true) – This ends the current response, no code below this statement will be executed and the user will be redirected to the target page.

Example:

int i = 0;
Session["ValueOfI"] = i;
Response.Redirect("webform2.aspx", true);
//After the above statement nothing would be executed
//So the Session["ValueOfI"] will contain "0"
Session["ValueOfI"] = Convert.ToInt32(Session["ValueOfI"]) + 1;

In the above code if you will check the value of the ‘Session[“ValueOfI”]’ on the redirected page it will be “0” as no code would be executed after the Response.Redirect.

But when you use Response.Redirect(url, false) – This redirects the user to the target page but continues the execution of the following lines of code.

Example:

int i = 0;
Session["ValueOfI"] = i;
Response.Redirect("webform2.aspx", false);
//Statements below this would also be executed
Session["ValueOfI"] = Convert.ToInt32(Session["ValueOfI"]) + 1;
//So the Session["ValueOfI"] will contain "1"

But here, if you will check the value of the ‘Session[“ValueOfI”]’ on the redirected page it will be “1” as even the code after Response.Redirect statement will be executed.

Example of How to Use Response.Redirect:

Following is a simple implementation of Response.Redirect:

public class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         //Check if user is still expecting a response or not
         if(Response.IsClientConnected)
         {
             //Simply Redirect the Page to webform2.aspx
             Response.Redirect("webform2.aspx");
         }
    }
}

Explaining the Code in the Above Example:

The above example is quite simple, on Line 6 inside the Page_Load event, we have a statement ‘Response.IsClientConnected’ this statement simply verifies that whether the end user is still connected and is expecting a response.

Inside the ‘if(Response.IsClientConnected)’ block we have used a ‘Response.Redirect’ statement to redirect the user to webform2.aspx.

What’s wrong with Response.Redirect:

As, I have foretold that ‘Response.Redirect’ has two overloads, if you are using the single parameter overload of the method, where we pass only the url then that is equivalent to writing –

Response.Redirect(<redirect_url>,true)

As, the default value for ‘endResponse’ argument is ‘True’

This is the main culprit. If you specify ‘endResponse’ parameter as ‘True’, then this method calls the ‘Response.End’ method for the original request, which throws a ThreadAbortException when it completes.

‘Response.End’ is not a very good method to be used, it was introduced in .NET 1.0 for compatibility with classical ASP. In order to end the current response, this method aborts the current thread and hence a ThreadAbortException is raised, which causes a performance hit. This exception has a negative effect on the overall application performance and hence is not recommended.

So what’s the alternative?

An alternative to the above issue is the use of ‘Response.Redirect’ by passing ‘endResponse’ parameter as false. This is fast, but as we know unlike Response.Redirect(url), the lines of code which follow the call to Response.Redirect(url, false) will also be executed.

So, what’s the solution to this? Well one solution to this is calling the HttpApplication.CompleteRequest() after calling the Response.Redirect method. Doing this is not exactly same as aborting the thread, which literally stops all the subsequent lines of code from executing.

But using this will execute the lines of code that follow the CompleteRequest() but as soon as the current page or module that calls this completes, the pipeline will jump ahead to the EndRequest event, thereby short circuiting the pipeline and the page will not be rendered.

The method HttpApplication.CompleteRequest() is accessible from HttpContext, so you can call it by writing as – Context.ApplicationInstance.CompleteRequest().

To make it more clear:

Bad Way of using Response.Redirect:

Response.Redirect(url)

Good Way of using Response.Redirect:

Response.Rediret(url, false);
Context.ApplicationInstance.CompleteRequest();

How Response.Redirect works internally:

When you perform a Response.Redirect then the resultant page simply returns a ‘HTTP 302 Found’ header. The ‘Location’ is set to the target page where you want to redirect i.e. the first argument of the Response.Redirect method. The ‘body’ of the response contains the HTML page, which in most cases won’t be rendered by the browser.

So, as an example if we write:

Response.Redirect(“Webpage2.aspx”)

Then the resultant response would be.

Result of the page

HTTP/1.1 302 Found
Content-Type: text/html; charset=utf-8
Location: http://localhost/
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 03 Jul 2015 09:15:56 GMT
Content-Length: 144

<html><head><title>Object moved</title></head><body>
<h1>Page moved to <a href=”http://localhost/Webpage2.aspx”>here</a>.</h1>
</body></html>

How does Response.Redirect differs from Response.RedirectPermanent:

Response.RedirectPermanent method was introduced in .NET 4.0. The main motive of this method is to specify the search engines that the page is moved permanently. In this post, whatever I have said for Response.Redirect also holds true for Response.RedirectPermanent with two exceptions:

  1. Unlike Response.Redirect the default ‘endResponse’ parameter for Response.RedirectPermanent is false.
  2. Redirect returns a ‘HTTP 302 Found’ header where as Response.RedirectPermanent returns a ‘301 Moved Permanently’ header.

Difference between 302 Redirect and 301 Redirect:

From a user’s point of view both 302 and 301 redirects are just the same and as an end user you won’t even notice whether a redirect is a 301 or 302 and it doesn’t matters much for you. But this is important from a search engine’s perspective.

A 301 redirect means for a search engine that the page has moved to a new location, permanently whereas a 302 redirect means that the move is temporary.

This information is quite useful for the search engines because as soon as a search engine encounters a page (say PageA) which redirects to another page (say PageB) with a 301 redirect (permanent redirect) then it can decide that there is no need to keep PageA in its search index as it is never going to be hit, so it only indexes the PageB.

Whereas, if PageA redirects to PageB with a 302 redirect, then it has to keep both the pages in its search index, as anytime PageA can stop redirecting to PageB because the redirect is temporary.

Example of how to use a Response.RedirectPermenant:

Below is a simple example of how to use a Response.RedirectPermenant method:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Response.IsClientConnected)
        {
            Response.RedirectPermanent("Webpage2.aspx");
            Context.ApplicationInstance.CompleteRequest();
        }
    }
}

And in this case the HTTP Headers will be:

Result of the page

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: /Webpage2.aspx
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 03 Jul 2015 09:15:56 GMT
Content-Length: 144

<html><head><title>Object moved</title></head><body>
<h1>Page moved to <a href=”http://localhost/ Webpage2.aspx”>here</a>.</h1>
</body></html>

Which type of redirect should be used when?

If your website is not a public facing website (not visible to search engines) then you can use any redirect method based on your personal preference. But in case, it’s a public facing website then for proper search engine optimisation below points can help you to understand which redirect should be used in which scenario:

Response.Redirect() – is perfect in the scenarios where your page is temporarily redirected based on some condition in code. For example:  when you need to redirect a user from login page after verifying his credentials.

Response.RedirectParmanent() – is good when you are permanently redirecting a page to another location and never plan to use the old location again. For example – if you have two different domains (say: domain1.com and domain2.com) for your website and always want the user and search engine crawlers to use only domain1.com for browsing/crawling your website.

So, this was all about redirects in ASP.NET. Hope you would find this post helpful.

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=""> <s> <strike> <strong>