Monday 22 February 2010

ASP.NET Session lost after Response.Redirect problem? You may just need to clear your cookies.

If you develop in ASP.NET soon or later you have come across a very annoying problem: the Session is lost after a Response.Redirect.

This is a such random problem that puzzled me and my colleagues in several occasions for quite long time.

Let's take for example the following snippet:


Session.Add("UserID", 1234);
Response.Redirect("/default.aspx", false);

This is adding the value 1234 to the UserID Session variable and then redirects the request to the default.aspx page. Note that the false parameter indicates that the Response should not end abruptly, instead the redirect will occur after the Page life cycle has loaded completely.
Bertrand Le Roy's article explains very well the reason why this is wise to do and I suggest you to read it if you haven't done yet.

So if you are still having the Session problem despite you are allowing the entire Page life cycle to load, then probably the problem may be much simpler than you think!


Basically the problem may well be related with the browser's cookies. In fact clearing you cookies may solve it!


Cookies are the mean by which a session can persist across different requests, the browser is identified each time through the session ID stored in a cookie.

I didn't have time to investigate what is exactly occurring, I'll spare this for next time when I'll update this post.

No comments: