Saturday, July 28, 2007

Session.SessionID is not unique

    I have seen many forums in which users are asking that Session.SessionID is not unique. You also have seen forums saying that "I am getting different value for SessionID on every page or in each post back." Yes they are correct !!!! "This is not possible. How can it be?", I know this is your reaction. We have read in all the books and seen practically that SessionID is unique, until user logs off or close the browser. This is also correct. Now you will say then why am I writing the story?

   Here is the actual fundamentals that I have observe practically. The session changes in each request (either post back or redirecting from one page to another page) until user has not insert any value in Session collection. This means server treats each request from new session if user has not entered any value in session. You can check this practically!!!

  Create a web application with two pages Default.aspx and Default2.aspx. Add one button and two lables on Default.aspx page. On page load of Default.aspx in if(!Page.IsPostBack) set any one lable's text to Session.SessionID. Now in click event of button set second lable's text to Session.SessionID. You can see that every time when post back occurs you have new value of SessionID. Amazing !!!!!!! You can check by redirecting to Default2.aspx page and print SessionID.

    Now, on Default.aspx page in if(!Page.IsPostBack) set Session["test"] = "1" or set any name value collection. Once you do this run the page. Click on button any number of time and you see that now SessionID is unique.

   Really Amazing!!!!

 

Happy Programming !!

3 comments:

Anonymous said...

IMO this is actually expected. The idea is likely that the server saves a bit of work by not trying to match a session for users that don't have anything in their session. Imagine for example if a site such as Google should match the session on each request for all users while it is usefull only for those that are authenticated. It could make a huge difference and the workaround is still very simple (just save whatever data you want to get the final sessionid).

Unknown said...

That behavior is quite understandable. If the session has nothing , then there is no point in saving the session . The asp.net will rather recycle it. This is little difficult to observe but you can see that sessionIDs are re-used.
But the observation is quite useful and thanks for your post.
Samir

DarKain said...

great aport

Thanks Man