ASP.NET: Session.SessionID changes between requests ASP.NET: Session.SessionID changes between requests asp.net asp.net

ASP.NET: Session.SessionID changes between requests


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;}


There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.

In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.

I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.


In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.