Seb Nilsson Seb Nilsson - 10 months ago 69
ASP.NET (C#) Question

ASP.NET: Session.SessionID changes between requests

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

I have a page like this:

SessionID: <%= SessionID %>

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

Answer Source

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.

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


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;