views:

322

answers:

2

Why does the property SessionID on the Session-object in an ASP.NET-page change between requests?

I have a page like this:

...
<div>
    SessionID: <%= SessionID %>
</div>
...

And the output keeps changing every time I hit F5, independent of browser.

I've seen this work correctly in other projects.

A: 

Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.

The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.

Mitchel Sellers
I am guessing my session timeout is not set to below one second. It changes with every rapid F5-press.
Seb Nilsson
+5  A: 

This is the reason

When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx

So basically, unless you access your session object on the backend, a new sessionId will be generated with each request

EDIT

This code must be added on the file Global.asax. It adds an entry to the Session object so you fix the session until it expires.

protected void Session_Start(Object sender, EventArgs e) 
{
    Session["init"] = 0;
}
Claudio Redi
I did not know that, never had an issue with it but that is interesting to know
Pharabus
@Cladudio could you just throw in one line of code and your answer is perfect.Interesting information coming out of an interesting question... plus one? ;)
Seb Nilsson
@Seb Nilsson: code added!
Claudio Redi