This page has been translated using an automatic translation service and the translation may not be very accurate.

Response.Redirect and Server.Transfer (English)

If you use this code and feel it is a useful tool, consider making a donation (through PayPal) to help support the project. You can donate as little or as much as you wish, any amount is greatly appreciated!

Italian page For the original Italian page, please click on the link: http://www.guru4.net/articoli/redirect-transfer/default.aspx

Introduction

In the realization of applications web it often turns out necessary to concur with the application to move itself between various pages that compose it, or to forward demanded to external documents to the same application.

While navigation of the pages is an obvious aspect from the point of view of the customer - and it is come true fundamentalally using link (tag < to >) HTML and the submit of form (and implicitly thanks to the ASP.NET serveur controls) - in order to concur to carry out rising of navigation also from the side of the application is necessary of the commandos that they act serveur side, and that in transparent way to the customer they make yes that is the serveur to decide that page the client will have to visualize.

The Framework NET introduces two alternatives in order to be annoying from a page web to the other using code serveur side, both without doubt known, but that in many cases they come used without knowing as effectively they act, what that in sure disagreeable situations can come useful and to avoid surprise.

These two alternatives are the methods Redirect and Transfer, pertaining respective to the classes HttpResponse and HttpServerUtility of the namespace System.Web, and that to the inside of a page aspx they are accessible through the objects Response and Serveur, from which the habit to refer to they like Response.Redirect and Server.Transfer.

HttpResponse.Redirect

A first look

This method concurs to impose to the client (browser) to demand the page indicated in its parameter of income.

The visible effect to the customer is that the browser it will visualize a various page from that in origin had been demanded.

Response.Redirect("nuovapagina.aspx");

What it behind the scenes happens is the shipment to the client, from part of the serveur, of an answer HTTP whose header it contains two differences regarding the answer that would have been generated from that page if the method had not been invocato:

  • code HTTP of the answer is 302 Found, that it means that the tried page has been temporary moved;

  • to the header the Location directive is hung, to flank of which the new address of the page is specified.

HTTP/1.1 302 Found
Server: Microsoft-IIS/5.1
Location: /nuovadirectory/nuovapagina.aspx

These two directives, together, force the browser to execute one new demand, of type GET, to the new specific resource.

It is luminosity from this short description that the Redirect method is leaned to a mechanism of protocol HTTP that would serve to other scopes, having made to believe to the browser that the demanded page has been moved, inducing it therefore to demand the new page specified in the Location directive.

Deepening

Up to now we have seen what happens behind the scenes and qual' it is the visible effect to the customer, but what happens to the page that it had been demanded originally?

In order to clear this concept it is necessary to know that the Redirect method introduces a overload, than beyond accepting a type parameter String of type chip ax an other Boolean.

Name Description
HttpResponse.Redirect (String) Redirige the client to the new specific URL and finishes the execution of the running page.
HttpResponse.Redirect (String, Boolean) Redirige the client to the new specific URL and if the execution of the page current must finish.

Naturally to call Redirect(String) is equivalent to call the second overload with the Boolean parameter place to true. In this case the execution of the page finishes.

But what means that the execution of the running page finishes?

Beh, means just literally that one. When in the tails-behind or inline of the page aspx it comes invocato the method Redirect(String) or Redirect(String, Boolean) with the Boolean parameter place to true the execution of the code is interrupted abruptly.
More just, it comes called the End method of the HttpResponse object, which it sendes all the output present in the buffer of the answer to the client, interrupts the execution of the code and triggers the EndRequest event, that it can be managed in the rows global.asax.

Consequently the page that comes sended to the client (in order to understand to us, that one that it contains the information for the redirect and the header with code 302) contains alone and only the content that until that moment had been generated, beyond to of the generated HTML of default from IIS, that it contains a link to the new page, which it comes generated probably for compatibility, in the case in which browser of destination the supports (currently all do not support it) redirect the automatic rifle through the directives of the header, and therefore concurring with the customer to manually follow the redirect cliccando on the link:

HTTP/1.1 302 Found
Server: Microsoft-IIS/5.1
Location: /nuovadirectory/nuovapagina.aspx

<html>
<head>
<title>Object moved</title>
</head>
<body>
<h2>Object moved to <a href='/nuovadirectory/nuovapagina.aspx'>here</a>.</h2>
</body>
</html>

In the case in which, instead, the Redirect method is called with according to parameter the place to false the execution of the page does not come finished but it proceeds until its conclusion, and in that moment it only comes sended client to the answer. The answer, therefore, beyond containing the information of redirect, contains also all the HTML generated from the previous page:

HTTP/1.1 302 Found
Server: Microsoft-IIS/5.1
Location: /nuovadirectory/nuovapagina.aspx

<html>
<head>
<title>Object moved</title>
</head>
<body>
<h2>Object moved to <a href='/nuovadirectory/nuovapagina.aspx'>here</a>.</h2>
</body>
</html>

<HTML>
<HEAD>
<title>Prima pagina</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form name="Form1" method="post" action="primapagina.aspx" id="Form1">
<input type="hidden" name="__VIEWSTATE" value="dDwtMjAwODAxNTcwNTs7PnF0SiGobsHq sJep5ADL4nmGZ1H" />
[... contenuto della pagina ...]
</form> </body> </HTML>

Since the content of this page does not come shown the customer, inasmuch as the redirezione happens immediately, would seem useless the possibility to specify if to finish or less the execution of the page. In truth, beyond to being however necessary in some situations, to concur with the page to finish its execution it serves also to avoid a problem inborn in the implementazione in the method and documented in this article of the technical support Microsoft.

In poor words the interruption of the execution of the page raises an exception of ThreadAbortException type.

Difference of performances between the two overload of the method

The fact to see to raise an exception can insospettire someone, since to raise of the exceptions is not generally one good practice from the point of view of the performances. However the choice must be estimated regarding the other alternative.

In other words, from the prestazionale point of view it is better to finish the execution of the page (and therefore triggering the exception) or to make it to continue on thread the current?

The answer is not univoca, why it depends on the page in examination. More simply, since as previously said in the case interruption of the execution the page all the its vital cycle does not come executed, and only subsequently it comes sended to the client with the information of redirect, is necessary to estimate if it will go to more heavy influence on the performances the generation than an exception or the elaboration of a page - comprised all its markup - not necessary, in how much will not never come visualized.

The ASP.NET team has evidently preferred to leave that it comes raised the exception, since the call to the Redirect method without the Boolean parameter the tax of default to true.

Property of the page passage and object redirect of data

Independently from overload of the used method, once reindirizzati to the new page differences between the two they vanish, and the result is that one of having a fresh page, completely independent from the page from which it is you leave yourself and in the bar of the addresses of browser the URL of the new page.

In this way, therefore, it would not seem possible to pass parameters from a page to the other use the Redirect method. In truth the passage of parameters possible if is carried out in explicit way through QueryString, simply calling the method hanging the braces nome/valore to the URL of the page in programmatico way. In this way the destination page will be able to approach these values approaching the QueryString property of the Request object.

The following code extension an example of redirect using a parameter of QueryString:

Response.Redirect("nuovapagina.aspx?nome=valore");

Famous: he is advisable to codify all the values passes from QueryString using the UrlEncode method to you of the HttpUtility class.

This is instead the code necessary in order to recover the values from the destination page:

string val = Request.QueryString["nome"];

Famous: he is advisable to operate on the values recovers from QueryString using the UrlDecode method to you of the HttpUtility class.

A last relative not negligible characteristic to the page that is possible to catch up through the Redirect method is the possibility to open an external page to the application, since, like approval, the call of the method in short is limited to a redirect carried out of the browser, which whichever page will be able therefore to demand one, a dynamic or static document is it.

Observations on the net performances

The Redirect method is much profit in order to move itself between the pages, but it is in sure cases not advisable, and quite contested, for the necessity of the two roundtrip da/verso serveur.

What means this? A roundtrip it is a "complete turn" of the distance of round-trip between client and the serveur.

Intuitably smaller it is the number of roundtrip carries out to you better are the performances of the net, the speed of the answer, and the cargo of the serveur.

I use of the Redirect method is much oneroso from this point of view, why it demands two roundtrip. The first one happens during the demand for the first page, than in its turn page (never visualized) containing the information of redirect will return to browser one. The second happens when the browser, in transparent way to the customer, it demands the page specified in the information of redirect and the serveur gliela sendes.
The visible result is therefore that one is obtained like answer page, but with two roundtrip. Evidently not optimal!

The described method of continuation, also creating visually an effect similar to that one of the Redirect method, introduces remarkable differences.

HttpServerUtility.Transfer

A first look

The method Transfer of the HttpServerUtility class serves in order to make one switch from the execution of one page to an other without to pass from the client, and carrying out all the operations serveur side.

The result that obtains is that the serveur receives the demand for the page, proceeded the demand but when it finds the invocazione of the method it interrupts the execution of the code of the page and begins that one of the page specified in the parameter of input of the method. To the client it comes therefore returned the new page without that it is shrewed of nothing.

This appears obvious also from the fact that in the bar of the addresses of the browser appears always the address of the first page. This why the client it is not to acquaintance of the operation executed from the serveur, and believes that the obtained page as answer is exactly that demand.

In other words, in this case not there are "trucchetti" of the serveur in order to force the browser to demand one new page, but it is the same serveur that gliela it sendes.

Deepening

After this short description some of the differences can be already intuire that characterize the method Transfer regarding Redirect:

  1. since it is the serveur to execute the elaboration of the new page, the parameter passed to the method can be only the URL of a present page on the serveur, otherwise it is not obviously in a position to elaborating it;

  2. the parameter must make reference to a page aspx, is not possible to demand an other type of resource;

  3. the execution of the running page finishes unavoidablly, since the answer will be only and be that one generated from the page towards which the transfer comes carried out. Consequently also in this case it comes raised an exception of ThreadAbortException type, from which it is not possible to svincolarsi.

Beyond to these enough intuitable differences, others exist some, that they represent of the rest the advantages that this method has in the comparisons of that one described previously.

Property of the page object of the transfer and passage of parameters

Like saying, in this case the transfer from a page to an other happens serveur side completely, and to the term of the elaboration of the destination page the answer only comes sended to the client. This concurs to maintain to a level of greater connection between the two pages object of the transfer, why the serveur has approached to both in the same moment and since all it happens in an only cycle of richiesta/risposta.

Before entering in the argument, also it is necessary here to know that also the method Transfer introduces of the overload.

Name Description
HttpServerUtility.Transfer (String) For the running demand, it finishes the execution of the page and begins the execution of the present specific page to the specific URL.
HttpServerUtility.Transfer (String, Boolean) It finishes the execution of the running page and executes the new page, concurring to specify if to maintain the present information in the collections QueryString and Form.
HttpServerUtility.Transfer (IHttpHandler, Boolean) It finishes the execution of the running page and begins one new demand using the personalized HttpHandler specific, concurring to maintain or less the present information in the collections QueryString and Form.

While I will not stop myself on the last one overload, that it comes used in various situations from that object of this article, is interesting to know the first two implementazioni.

Optional the Boolean parameter concurs to specify if to maintain or less the present information in the Collections QueryString and Form of the page in which it has been invocato the transfer. If this does not come specified the information they come maintained of default.

This behavior concurs to approach the present information in the previous page also from the page towards which the transfer is carried out, concurring therefore with the two pages to share information.

In the new page, therefore, it will be possible to use these information through the property exposed from the Page object:

Request.QueryString["nomeParametroQueryString"];
Request.Form["nomeParametroForm"];

If the advantages in the passage of data were limited to these, however, the method Transfer would not be much more interesting of the previous one, from this point of view.

An other way exists in fact in order to pass given between two pages using this method. This technique closely is not tied to the method Transfer, but it is concurred from the characteristics of the HttpContext class.

This object, accessible through the Context property of the Page object, contains all the information correlated to the running demand, comprised the objects Request, Response, Serveur and therefore via.

Beyond to all these indispensable information, it exposes a property, Items, that it implements the IDictionary interface and it is in a position to containing a whichever type of object that we want to insert to you.

The important characteristic of this object is that it has a duration of life that goes from the beginning to the end of the running demand. That concurs to approach to you in whichever point of the demand.

While in the greater part of the cases its Items property does not turn out very useful in order memorizzare values, since since the life of one demanded hard from the demand for the page to its shipment to the client is not necessary to conserve given from the moment that after the shipment of the page its content automatically would be eliminated, in this case, instead, in which the pages that come elaborated during the cycle of life of an only demand are instead two, the possibility memorizzare values to its inside during the execution of the first page concurs to have them still available, and always in the same place, also during the execution of the second one.

In order to clear this concept, than to words much more it is complicated that in the truth, here an example.
The first page ago inserts values to the inside of the Context.Items object and a transfer to an other page:

Context.Items["nome"] = "valore";
Server.Transfer("nuovapagina.aspx");

The second one, in a whichever point of its elaboration, can recover them in the same way, since the Context object is the same one before, even if acceduto from two different requests of page:

Response.Write(Context.Items["nome"]; // stamperà la stringa "valore"

It is important to hold in consideration that in this way it is possible to share given of whichever type, since the Items object can contain arbitrary objects. Naturally, in order to recover them, it will be then necessary to carry out a cast opportune in order to obtain an object of the wished type. But it is obvious that from the point of view of sharing of data between the two pages in issue the advantages are remarkable regarding the Redirect method.

Observations on the net performances

This aspect is an other advantage to favor of the method transfer, since, like it appears by now obvious, it does not demand a roundtrip additional, but all the operation is carried out on the serveur, and the answer comes sended an only time for every invocazione of the method.

Observations on the emergency

Since using this method new demand to the serveur does not come carried out one but the data of the demand are used originate them, are not possible to verify that the client it is authorized to obtain the resource that comes sended as a result of a Transfer. In the case in which it is therefore necessary a control of this type will have to be previewed of the techniques of personalized authentication and authorization.

Observations on the usabilità

Like pointed out previously, using the method Transfer the address visualized on the bar of the addresses of the browser does not change but that one of the first page remains. In some cases this can confuse the customer.

Unusual behaviors

In order to conclude the argument, it is worth the pain putting in evidence a situation that can introduce the case in which the first page something on the buffer (through Response.Write) of the Response object writes as an example and this does not come emptied before the transfer to the second page.

We distinguish however two cases:

  1. The Buffer of the Response object is disattivato, that is the content comes sended directly to the client without buffering;

  2. The Buffer of the Response object is activated, that is its content comes sended all in once to the term of the elaboration of the page.

The behaviors that are obtained are following:

  1. In this case the data of the Response already have been send to you and not there is way to eliminate them. Consequently in the destination page the output it will contain (in head) also those data that had been written from the first page;

  2. In this case, instead, with the method Response.Clear() he is possible (and advisable) to eliminate them before executing the transfer.

Conclusions

As we have seen also two methods commonly use you introduce of the interesting characteristics that often do not come held in consideration during the choice which to use. To be with the current of the peculiarities, the advantages and the disadvantages of everyone concurs to carry out one chosen aimed.

Online of the all general, the criteria guide for the choice can be reassumed in the following points.

He is necessary or preferibile to use the Redirect method when:

  • A not present resource must be demanded on the same serveur of the page begins them;

  • An advanced mechanism of passage of parameters is not necessary;

  • Problems of imbottigliamento of the net or cargo of the serveur are not had;

  • It is not needed of a connection tightened between the two pages.

Viceversa, will be necessary or preferibile to use the method Transfer when:

  • The resource is present on the same serveur of the page begins them and is one web form (with extension aspx);

  • It is necessary a reliable mechanism and more complex than passage of the parameters;

  • The cargo of the net and the serveur is wanted to be reduced;

  • Not there are requirement of relative authentication and authorization you to the destination page;

  • A strong connection between the two pages is wanted to be maintained, so that beyond to the values it passes to you explicitly share also all the information inborn in the objects that have one duration of life limited to the duration of the demand.