ASP.NET Sessions

Did you know that if you don’t put anything into an ASP.NET session, it will generate a new one with EVERY page request!!???

Try it out for yourself…

  • Create a new MVC(3/4) Web App in Visual Studio.
  • Choose the Razor rendering engine
  • Add the following code to index.cshtml

Run the website and you will see that the Session ID is different every time you click back to, or refresh the index page!

At first I though this was because I wasn’t logged in. If I go to the Register.cshtml page and create a new account, and login with it, this behaviour still persists.

It’s only when you add something to the session that you see the same Session ID being reused.

Go to the About.cshtml page and add the following code:

Run the app again, and make a note of the Session ID on the index.cshtml page. Next click the About menu tab, and then go back to the Home tab. You will see that your Session has been persisted because you added today’s name into the collection.

Why does it work this way? I’m not really sure. If you have any ideas, I’d be happy to hear them.