Another breaking change in ASP.NET 2.0: Session.SessionID

.NET, ASP.NET, Technical stuff
See comments
I only recently became aware of another breaking change in ASP.NET 2.0: In order to optimize session state management, some changes have been implemented. One of the most puzzling ones when you’re not aware of it can be reproduced as follows:
  • In ASP.NET 1.1, create a new web application.
  • Add a label to the page, name it lblSessionID.
<asp:Label Runat="server" ID="lblSessionID" />
  • In the code behind, add the following code in the “Page_Load” method:
protected void Page_Load(object sender, EventArgs e)
{
  lblSessionID.Text = this.Session.SessionID;
}
  • Load the page in the web browser. Press F5 as many times as you like, and the SessionID remains the same.
This behaviour is expected, and my guess is that quite a few applications rely on the SessionID being consistent on every page refresh.
However, in ASP.NET 2.0, the behaviour is different, which may cause applications to break: If you create a new website (or a new web application) and reproduce all the steps above, the SessionID will be different on every refresh of the page. The reason is found in MSDN:
“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.”
Since cookie-based session state is the default, this change of behaviour will affect existing web applications relying on the SessionID to identify the current user without having previously stored data in the Session object.
Here is a possible fix:
protected void Page_Load(object sender, EventArgs e)
{
  if ( this.Session[ "dummy" ] == null )
  {
    this.Session[ "dummy" ] = 1;
  }

  lblSessionID.Text = this.Session.SessionID;
}
 
Not very elegant, and I can’t say that I totally understand the reason why the ASP.NET team doesn’t offer a better way to keep the SessionID consistent all the time, even when nothing is stored in the Session object. Anyway, this has caused me a few headaches, so hopefully this article will help other developers.

This post was imported from my old blog. Original comments screenshot:

2016-01-11_16-48-03

Previous entry | Next blog entry

Comments for Another breaking change in ASP.NET 2.0: Session.SessionID