Friday, September 12, 2008

Session lost problem after Response.Redirect

If you create a session like this and redirect the user to some other page, the session will lost.

Session["UserId"] = "User1";
Response.Redirect("YourPage.aspx");

This is because of the working of session and Response.Redirect, Lets go through.

" When you create a new session (that is, the first time you write to a Session variable), ASP.NET sets a volatile cookie on the client that contains the session token. On all subsequent requests, and as long as the server session and the client cookie have not expired, ASP.NET can look at this cookie and find the right session.

Now, what Redirect does is to send a special header to the client so that it asks the server for a different page than the one it was waiting for. Server-side, after sending this header, Redirect ends the response. This is a very violent thing to do. Response.End actually stops the execution of the page wherever it is using a ThreadAbortException.
What happens really here is that the session token gets lost in the battle.
There are a few things you can do to solve this problem.

First, in the case of the forms authentication, we already provide a special redirect method: FormsAuthentication.RedirectFromLoginPage. This method is great because, well, it works, and also because it will return the user to the page he was asking for in the first place, and not always default. This means that the user can bookmark protected pages on the site, among other things. " - Bertrand Le Roy

Another thing you can do is use the overloaded version of Redirect:

Response.Redirect("YourPage.aspx", false);

This does not abort the thread and thus conserve the session token. Actually, this overload is used internally by RedirectFromLoginPage.

1 comment:

Jeff said...

Thanks so much!. I've spent about 8 hrs trying to figure out why I was losing my sessions.