Tuesday, January 15, 2008 11:37 AM
A colleague was running into a problem with his session values. He had a page that had some custom timeout code written in. This code outputs a refresh metatag to the header of the page, and if no activity occurs in 60 seconds it redirects to a "Please re-login" type of thing.
In this re-login message page, he was trying to check whether this was a new session (someone hitting the redirection-page directly) or if it was an existing one coming from one of the pages with the timeout code.
He was using Session.IsNew to test this...but was running into a problem: every time he would run the code, it would return true: the session was *always* new.
But how can this be? We've already created a new session by visiting the previous page hadn't we? Well, yes...but we also created a new session variable when we visited the redirection page.
Remember that the web is stateless, and remains such unless some outside force determines that it doesn't need to be...like ASP.NET session. Try this:
Create a webpage and put two literal controls on it: one for the Session ID and one for the IsNew property of the session.
Add a button that just does a postback, and wire up the code so that the SessionID and IsNew values write out to the literals (or response.write or however you want to do it...just get it to the screen).
Every time you hit the button to trigger a postback, you will get a NEW SessionID value, and the IsNew property will always return true.
Now add an extra bit of code to your page load: Create a session variable and assign some value to it.
Now when you run the page, the first load will show the IsNew property as True, but every button click afterwards will show False and you won't get a new Session ID value.
At first this might not seem to make sense, but when you think about it, it does: every time you request a page, the site will think that its happening for the first time (stateless) UNLESS there's some reason to think otherwise (i.e. assigning some value to the session to maintain it accross postbacks and navigation). I think our default thought is that we automatically just get a session value when we visit a page and we keep it until the timeout expires, but that's obviously not the case.