Posts Tagged ‘Sessions’

ASP.NET Sessions Part 6 – Abandoning a Session

Friday, March 13th, 2009
This entry is part of a series, ASP.NET Sessions»

If you want to terminate your session and effectively wipe out all variables in it, call Session.Abandon().  Although you can reset your session variables back to Nothing, this will also notify ASP.NET to clear the session up and call the event handler in Global.asax to deal with the session end (I think that this is the only way that this ever actually gets fired, but I could be wrong).

ASP.NET Sessions Part 5 – How Long Does a Session Last?

Thursday, March 12th, 2009
This entry is part of a series, ASP.NET Sessions»

Bearing in mind what I posted in earlier parts of this series of posts on sessions, you may find that other factors cut short your users’ sessions – see the earlier posts about this.

You can set the timeout of your sessions using the “timeout” attribute of the “sessionState” element in web.config.  This is a value set in minutes, and is the idle time before a session expires.  That means that the time is measured from the last request (not sure if it is measured from when the request is started, completed or some random point in the middle).  It isn’t measured from the start of the session or anything. 

The maximum value is 525,600, which is the number of minutes in a year (assuming it is a non-leap year).  This maximum value apparently only applies to the in process and state server modes (I’ll be amazed if anyone manages to keep a session going that long in either of these modes without dedicating a server to it!).  

The default value is 20 minutes.

Note that changing this has absolutely no effect on classic ASP sessions – they operate completely independently.  I’m pretty sure nothing in web.config will ever really affect them.

ASP.NET Sessions Part 4 – Configuring how the Session Variable Data is Stored on the Server

Wednesday, March 11th, 2009
This entry is part of a series, ASP.NET Sessions»

ASP.NET gives you several alternatives for how the session data is stored on the server (remember that the clients just get a key to uniquely identify their session – not all the information is stored on their machines in cookies or anything).

  1. In Process
  2. State Server
  3. SQL Server
  4. Custom

These can be set by using the “mode” attribute of the “sessionState” element.

The “InProc” value (in-process) means that IIS stores the session state information within memory in the process that it uses for running the applications.  This is the default setting and is ok for many situations, but it has some big downsides.  All sessions are reset when the IIS process is recycled, which usually happens pretty randomly.  Also, all sessions are reset if you do a major rebuild of the site (which can be more of a pain than you think, especially as ASP.NET might do this behind the scenes if you change something in the App_Code folder).  The main advantage is that it is easy to configure and works out of the box.  Another advantage is that the data in the session state variables doesn’t have to be serialisable.

The “StateServer” value means that ASP.NET should look in the “stateConnectionString” attribute to find a connection string to connect to an ASP.NET “state server”.  A state server is a service which comes with ASP.NET (it doesn’t run by default – you’ll need to start it up and set it to run automatically when Windows starts).  You can find it in the folder %windir%\Microsoft.NET\Framework\VersionNumber\aspnet_state.exe .  Note that this doesn’t need to run on the same machine as IIS is running on, but it is probably sensible to run a state server of the same version as the version of IIS.  I’ve never used this myself though, so I can’t tell you how well it works.  The default connectionstring is to connect to the current server.   I expect that this will need data to be serialisable and will be able to retain the data as long as the sessionstate service isn’t restarted (even if IIS is).  It won’t retain data if the sessionstate service (or the whole server that it is running on) is restarted though.

The “SQLServer” option is my favourite.  This looks in the “sqlConnectionString” attribute for a connectionstring to an instance of SQL server which is configured for storing session state information.  ASP.NET 2.0 also added the “allowCustomSqlDatabase” element, which can be used to specify whether to use a customer SQL database instead of the default one.  nb.  You’ll need to setup SQL server for this, which you can either do by running the SQL script  %windir%\Microsoft.NET\Framework\version\InstallSqlState.sql or by using the Aspnet_regsql.exe utility to do it for you.

The “Custom” value allows you to specify your own class which is responsible for storing state information.  You’ll need to also add it to the providers section within the sessionState element and set the “customProvider” attribute to the name of the provider type.  Your custom class will need to inherit from SessionStoreProviderBase.

There is also another value – “Off”.  This turns off session state information being stored at all.

ASP.NET Sessions Part 3 – Maintaining the Session Data Across Multiple Requests

Monday, March 9th, 2009
This entry is part of a series, ASP.NET Sessions»

In order to maintain the data on the server across multiple requests by the same user, the server needs some way of identifying the user.

You may think that this can be done by IP address, but there are a couple of problems. Firstly, there is no guarantee that people are going to have a constant IP address – they may have multiple internet connections and a load-balancing router which will share their requests out among the different connections (this is becoming more and more common). Secondly, they may be accessing the internet via a common invisible proxy server or a common NATed router which will mean that multiple users may appear all on the same IP address.

That means that we need to find another solution. ASP.NET provides us with 2 alternatives. We can use cookies, or we can use unique URLs (web addresses) with a session key encoded in them. By default, ASP.NET uses cookies, but not all clients support them (some paranoid system administrators turn them off). ASP.NET also presents us with an automatic mode, which is designed to detect whether cookies are available and if not, encode the key in the URL. In my experience, this doesn’t always work.

The other problem with encoding the key in the URL is that ASP.NET can’t always reliably rewrite all URLs. It works pretty well, by encoding it as virtual directory, but this looks messy, and of course it creates problems if people bookmark the URL. It also loses the session if the user clicks a link which takes them to another site and then the site sends them back, or if the user retypes the original URL.

The sessionState element in web.config has an attribute called “cookieless”, which can be used to control whether cookies are used.

If it is set to “AutoDetect” (I think this is default), ASP.NET attempts (not reliably in my experiece) to detect whether the connecting browser supports cookies and use them if possible or if not fallback to URLs.

If it is set to “UseCookies”, ASP.NET will always try to use cookies, but they might not work.

If it is set to “UseDeviceProfile” (I think this is new in .NET 3/3.5 – not sure), ASP.NET uses System.Web.HttpBrowserCapabilities to try to find out whether the browser supports cookies. MSDN seems a little hazy on how this works exactly, but I would guess that it is via the headers that the browser passes in the page request.

If it is set to “UseUri”, ASP.NET will always use URLs, irrespective of whether cookies will work. I have had to use this setting at least once.

From ASP.NET 2.0, you are able to specify the cookie name if you are using cookies (it defaults to “ASP.NET_SessionId”) by specifying it in the “cookieName” attribute.

If you aren’t using cookies, there is also an optional boolean attribute called “regenerateExpiredSessionId”, which can be used to control what happens when a user comes back after the session has timed out with an old session ID.

ASP.NET Sessions Part 2 – accessing session state variable data

Wednesday, March 4th, 2009
This entry is part of a series, ASP.NET Sessions»

To add/set a session variable, from within code on a page, you can simply use

Session(“VariableName”) = Value

To reset it, you can set it to Nothing in VB.NET or null in C#

If you aren’t inside a page’s code, you can use the HTTPContext class to get the current context and access the session via that (more coming on HTTPContexts at some point in the future).  You can do this like…

HTTPContext.Current.Session(“VariableName”) = Value

ASP.NET Sessions Part 1

Tuesday, March 3rd, 2009
This entry is part of a series, ASP.NET Sessions»

ASP.NET provides you with a method of storing data per session.  A session is related to the current user at the present time.  When it operates correctly, a session will span multiple requests for the same user.  This is very useful for example for allowing a user to login and storing their user ID in a session variable (although ASP.NET has other mechanisms for maintaining site logins, I am using this as an example).  There are several factors to consider when using sessions: –

  1. How will ASP.NET maintain the session across multiple requests (how does it know that different requests come from the same user)?
  2. How will the session variables be stored on the server?
  3. How long does a session last?

There are probably other factors, but these are generally the most important ones in my experience.  Each of these factors can be controlled from the configuration/sessionstate element in web.config.  I will go into more detail about this in future posts.  Before that, I will explain how to access the session variables at all.