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.