Friday, May 22, 2009

SessionID in .NET 2.0

Most of the asp.net developer has assumption that SessionID doesn't change through out the session of any user.
The above statement holds good completely in .NET 1.1 and partially in .NET 2.0.

Let's examine the behaviour of SessionID in .NET 2.0

Create a aspx page, copy and past below code in codebehind of Page_Load.

Response.Write(Session.SessionID);

Now run the application, you will get sessionid on the page.
Now examine below steps:
1. Open new browser using CTRL + N, you will get different sessionid now.
2. Open new browser using File -> New, you will again get different sessionid now.
3. Copy the url and paste it into another tab of the browser, you will again get different sessionid now.

Above behiour only happens in .NET 2.0. In .NET 1.1 sessionid will remain same.

Create another aspx page, Copy and paste below line of code in codebehind of Page_Load

Session["Test"] = "testing";
Response.Write(Session.SessionID);


Now run the application, you will get sessionid on the page.
Now examine all the above three steps, this time you will get same sessionid in all the three steps.
So, whenever Session object will be used, SessionID will be same.

Session information gets stored in the cookie, so when cookie based session is used(Other is url based), ASP.NET does not allocate the cookie until Session object is used.

Therefore SessionID get generated for each page request until Session object is used.

No comments:

Site Meter