2

I'm a little confused about the life cycle of the session in ASP.NET, here is my test case.

A user logs in, I save some info to a session variable (e.g. Session["bob"]="bob") then I do an "IIS reset". The user is still logged in, but the session data is null (e.g Session["bob"].ToString() throws a NullReferenceException.

I expected the session data to still be around. Is there something I can do, other than log out the user? I expected the session data to be around as long as the user is still logged in.

Any good links so I grok what's going on, as well as any help with the actual issue is greatly appreciated. I tried to Google this, but wasn't able to frame the question in a way to get what I wanted.

Adrian Clark
  • 12,449
  • 5
  • 36
  • 42
Eric Brown - Cal
  • 14,135
  • 12
  • 58
  • 97

2 Answers2

7

The behavior you are seeing - where the Session contents do not survive an IIS reset event - is due to where the Session values are stored. By default these values are stored within the memory of the ASP.NET "Worker Process", which is the program which runs your ASP.NET web site.

When you perform an "IIS reset" you shut down the entire IIS server, including the ASP.NET Worker Process. This means that the contents of the Session are removed from memory. Your user still appears to be logged in because that is controlled by the cookie stored in their browser. If the cookie is still valid, the login is.

If you wish your Session state to survive an IIS reset (or anything else which causes the ASP.NET worker process to restart) you'll need to store your Session objects in another place. This is fully supported by ASP.NET by using different Session storage "Modes". Read about those in the MSDN article "Session-State Modes".

For a general overview of the Session, check out the "ASP.NET Session State Overview" article on MSDN.

Adrian Clark
  • 12,449
  • 5
  • 36
  • 42
0

yah its right but some time its happen then session no remove properly at that time

you have to check session like

If Session("username") = nothing then

Response.redirect("~/default.aspx")

End if
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
Bhargav Mistri
  • 944
  • 8
  • 20
  • What event in Global.asax should I test this in? I thought I rememberd doing it before, but I'm failing, finding the right event. – Eric Brown - Cal May 05 '11 at 19:24
  • Will Sessio["bob"] not always == null in session start, thus it will always redirect you to the login page, even the first time when I'm trying to login?? – Eric Brown - Cal May 06 '11 at 14:21
  • but you don't have to write this in login page.. you may be write this code in other page like.. master page on load event – Bhargav Mistri May 07 '11 at 14:37