Share via


Server.Transfer / Response.Redirect

Server.Transfer and Response.Redirect are causing a new page to be processed, but the big difference is how they are doing it.

- Server.Transfer terminates the execution of the current request (Response.End) and begins execution of a new request using the supplied url. No trip back to client is performed.

- Respose.Redirect creates a special header, sends it to the client to ask the server for a different page.

o Response.Redirect(url) == Response.Redirect(url, true). In this case, right after creating the header, the page execution is done – Response.End is called, and this one causes the current thread to be aborted (ThreadAbortException will be thrown).

o Response.Redirect(url, false) doesn’t abort the thread, so it is recommended because it avoids the exceptions. This form is used for example by FormsAuthentication.RedirectFromLoginPage method.

Therefore, if we are changing Session items and then call Response.Redirect(url) or Response.Redirect(url, true), the session items are not saved, so they will not be there when url is executing (see this post for a brief explanation on how session works). Eg., when we want to log in a user, the following code won’t work:

Session["UserName"] =username;

Response.Redirect("~/default.aspx");

Response.Redirect(url, false) works, because we are not calling Response.End and session is saved.

What about Server.Transfer? Because the transfer happens without a trip back to the client (compared to Response.Redirect, it saves one client/server round trip), the page collections of the first page are simply used by the second. The drawback is that the user seems the same URL as for the first page and is unaware of the change. Relative links / image paths may not work if the new page is a different directory.

In my previous post, I talked about a session race condition when calling Server.Transfer between pages with different session modes. The problem wouldn’t have been seen if Response.Redirect would have been used instead. Of course, Response.Redirect might not suit other requirements that application had.

Comments