Session.SessionId is *not* unique

A co-worker of mine was trying to detect whether his session expired in an ASP.NET application. Before he discovered Session.IsNewSession, he was using the SessionId variable and comparing it to hidden values and whatnot. He had assumed that when a page was reloaded after the session expired, that a new SessionId would be created. This is not always true.

There's a countdown timer (by default, 20 minutes) that fires from the first request for a users session. If there is another request efore the timer reaches zero, then it resets the counter and begins again. When it reaches zero, the Session_End event (in global.aspx) is fired, not because of a request but because the timer ran out.

Session.SessionId might be the same on a postback or page reload. If you're not writing any data to the session, ASP.NET will reuse the Id because from it's perspective it hasn't changed so why create a new one (id, not session)? Session.SessionID is generated in RAM on the server and not a persistent property. It's unique at the time is it created, but not guaranteed to be unique over the course of time. For example, if IIS is restarted it may restart the numbering sequence.

So use Session.IsNewSession to determine if it's a new session or not. Use Guid.NewGuid() to create something unique (you can store this in a Session variable and check for it later if you want).

There's a great FAQ on ASP.NET session here in case you're interested.

Happy coding...

1 Comment

Comments have been disabled for this content.