ASP.NET Session State IsNew – or is it?

A new session ID is generated for each request in applications that do not store data in the session dictionary.

Yes it’s amazing, but true. Logically you’d expect a new ASP.NET session object to be created when the user arrives at your site, and then expire 20 mins (or whatever you configure) after they leave, but in fact a new instance is created for each request, until (if ever) your code sticks some data into session state.

The reason for this is performance – at the end of the request life cycle any data placed in Session state is serialised and persisted using your chosen provider. If there’s no data, then ASP.NET skips the taks of maintaining the session ID and loading this again next time.

If you’re using the default InProc mode then the performance gain might be negligable, but if you’re for instance using SQL server then the job of adding an empty record to the session state tables, and reading this again (for no purpose) is very sensibly skipped.

What this does mean however is that the Session IsNew property will return true until you use Session State – so don’t use this flag to check if a user has just arrived at your site. If you need to check this you could place your own cookie to expire with the session (i.e. don’t set the cookie’s Expire property).

Key thing is – Session State might be new, but that does not mean your user’s session on the webserver is.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: