ASP.NET MVC - Session cookies seem to expire faster than timeout set? - asp.net

I store some data in Session cookies.. like User ID for example. I set the timeout to expire in 60 minutes like so:
<configuration>
<system.web>
<sessionState timeout="60"></sessionState>
</system.web>
</configuration>
But there are times where it is expiring as fast as 10 minutes or so. I cannot figure out why. Is there something I am missing?

The default session provider for IIS/.NET is InProc, which is short for In Process (i.e. volatile memory). What this means is that, if for any reason, the process restarts, all session data will be lost as the data stored within the process is lost when the executable restarts / is shut down. IIS web applications will shut down after some period of time by default, which would cause all session data to be lost. This can also include starting and stopping debugging sessions (per comment below).
Another possible issue would be if you are deploying to a server farm. InProc sessions cannot be shared across multiple web servers.
If you are deploying to a single server and you can control the configuration, check to see how often the process (App Pool) is set to recycle or timeout. You may want to increase this timeout period to better suit your session requirements.
If you are deploying to a web farm (more than one machine or cloud hosted) or cannot control the server configuration, then you should look at implementing something like Sql Session State provider in your application. This will provide a sole source for storing session data that can be shared between multiple web servers as well as the data is stored independent of the running process, so it will survive process restarts/crashes.

Try to Log reason for your session expire
Set web.config
<configuration>
<system.web>
<sessionState mode="InProc" timeout="20"></sessionState>
</system.web>
</configuration>
On global.asax
void Session_End(object sender, EventArgs e)
{
// Write your code to capture log
}

Related

Session variables being lost before session expires

After a user logs in, I set a Session variable to to store their ID. This ID is used to load things like their user name. The name will show correctly at first, showing that the Session variable was used. However if I refresh the page after just a few minutes, the user name is blank, suggesting the Session variable is now gone.
I've read that the default Session timeout is 20 minutes. I confirmed this in my hosting provider's Asp.net settings. But the variable is lost well before 20 minutes.
I also read that I should have a Global.asax file with the below code:
void Session_Start(object sender, EventArgs e)
{
Session.Timeout = 20;
}
I did that, but I'm still losing the variable after a few minutes. I then read that I should place the below code in my web.config:
<configuration>
<system.web>
<sessionState mode="InProc" timeout="120" />
</system.web>
</configuration>
So I did that, but then it produced an error saying: "Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS."
I'm not sure what else to try. The website I'm creating is in a sub-directory on my domain, the web.config and global.asax files I edited are in that sub-directory, so I wouldn't think there's a conflict elsewhere right?
Your subdirectory is not marked as an application in IIS. This could be part of the problem as you haven't created the application properly. Since it's not marked as an application, certain features of your web.config are illegal since they can only be placed into the root directory of an application.
Other factors though can be the application pool has recycled for some reason. Sometimes due to errors, but also do to other events such as running out of database connections in the connection pool as well as the most famous which is simply storing too many items in session that causes the app pool to run out of memory and recycle.
Since your application is in a subdirectory, it is actually part of another application. In this case anything going on with the main application could be interfering or abandoning the session. The root web.config could have very different session state settings which could make the behavior very different.
Start by setting the sub-directory as an application in IIS and see how it then behaves. After that, if the problem persists start to look for other issues such as memory leaks. You don't want to keep the session extended for too long either. If a user stops doing anything for more than 20 or 30 minutes, chances are they aren't coming back anytime soon. Since session eats memory, having shorter times helps the performance of the application. If you need longer duration storage, it's generally better for performance as well as the application's stability to use a store made for longer term data such as a database.

ASP.Net Session.Timeout - Is StateServer and Programmatic Session.Timeout Good Enough?

Reading around, it looks like changing asp.net session time when using the InProc model requires two changes...
web.config - Application Pool Idle
Timeout - Seems you should set this >= Session.Timeout
I gathered this from reading http://asp-net.vexedlogic.com/2012/05/23/aspasp-net-session-timeout-how-do-i-change-it/.
So, if I don't have the luxury of changing timeouts on application pools, I'm wondering if I change to use StateServer and then programmatically set Session.Timeout as described in the article above, do I need to worry about what web.config #timeout and application pool idle settings are set at? Will my two actions take care of everything?
If it does take care of it, I guess the next question is whether or not anyone knows how performance compares from InProc vs StateServer.
Thanks in advance.
From my understanding, if you switch from in-proc to state server the idle timeout (in IIS) setting won't have an effect on your session state timeout.
There will still be worker processes that may be terminated in the application pool if there is no activity (if the idle timeout is passed) but the session state (i.e. the user session and application session values) will be maintained beyond this. Your session timeout should just be controlled by the timeout value set in the configuration (from here) i.e.
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=SampleStateServer:42424"
cookieless="false"
timeout="20"/>
</system.web>
</configuration>
Inproc is faster than StateServer as your session data needs to be serialised / deserialised when it's stored. It may also be stored on a separate machine which may introduce some latency. But of course there are the advantages of State Server i.e. Session state persistence between application restarts (app pool recycling), state can be shared across multiple servers in a web-farm.
This question also discusses pros and cons of using the State Server mode.

Asp.net Session expiring automatically after few seconds

When user login i am storing user_id in Session variable and on second page i am checking on page load if user_id exists then fine, otherwise redirect to sign in page but when i login and and redirected to next page after few seconds when i refresh page my session is null there and i am redirected to sign in page its happening in whole application i have tried all solutions but all in vain
Another thing is that application working fine on development server and also on local IIS in LAN but on live server this issue is occurring.
Kindly suggest solution, i am also defining session time out in minutes and mode in Proc in web.config.
Thanks in advance
If you are using InProc session state mode and multiple worker processes in the application pool then Session might expire automatically after few seconds as data loss can occur if different requests for the same session are served by different worker processes.
In my case, I am using InProc session state mode with Maximum Worker Process set to 4 hence session was expiring.
Setting Maximum Worker Process = 1 solved it.
You can add <httpRuntime delayNotificationTimeout=""/> in your web.config. see more
OR
Try this
<authentication mode="Forms">
<forms loginUrl="/loginurl" timeout="2880" />
</authentication>
try this in web.config
<configuration>
<system.web>
<sessionState mode="InProc" timeout="90"></sessionState>
</system.web>
</configuration>
One session issue I just ran into, which may help here, is that users from certain companies would have their sessions end fairly quickly but other users had no problem. After doing a lot of testing, I found that users connecting to the website from their office were having problems but the same user connecting from home had no problem.
Their company is setup to use a single IP (or set of IPs) for all out bound web requests. Well, this company had multiple IPs for out-site access and that IP changed (or could change) with each request. This would reset the session on my website and log them out.
I am still in the process of implementing a fix or a check for this so I can't give you a fool proof fix, but it is something to look into. This would explain what is happening to you.
Any chance you're using a cluster of servers? Network load balancing might reroute the client to a different server every time. If so, either the NLB has to be reconfigured to keep a client on a single server or set up session sharing.
Also check that the application pool doesn't have some obscene rule to recycle itself too often.

Updating an existing asp.net website kicks off users

When I update an ASP.NET Website [note: it's not a Web Application] running on a customer server by overwriting it with the latest version it currently kicks all the users off.
I'd prefer to be able to deliver a new version of a site without kicking off users - is there a way to minimise the chance that users will get kicked off? [apart from the obvious one of waiting for a time of low-usage]
If I moved from InProc to Session State I guess this might do the trick - but is there any other method?
Chaning away from InProc Session State should help.
The problem now is that any time your app is reset in IIS (overwriting the web.config will cause a restart), the IIS Worker process restarts and clears your session info.
Check out this MSDN Page to read the limitations of In-Process Session State:
Session State - MSDN
I think additionally to what you are suggesting, it will be appropriate to display an "update in progress..." page instead of kicking off users. You can do that by changing your web.config file.
Session IDs are valid for the lifetime of the application pool, or until (I believe) 20 minutes following the last page request from the client in question. This is configurable in web.config:
<configuration>
<system.web>
<sessionState
cookieless="false"
timeout="20"
</sessionState>
</system.web>
</configuration>
If the application pool is recycled, files within the application are updated, etc, your session IDs will be invalidated. For this reason it is considered wise to deploy your site during off-peak hours.
Design your application to not rely on the existence of session state variables. Use cookies for authentication (or integrated auth) and check for session variables as you use them; reload them if they don't exist.

Asp.net forms authentication cookie not honoring timeout with IIS7

Authentication cookies seem to timeout after a short period of time (a day or so). I am using Forms Authentication and have the timeout="10080" with slidingExpiration="false" in the web.config. With that setting, the cookie should expire roughly 7 days after the user is successfully authenticated.
This worked as advertised with IIS6, but when I moved the site to IIS7, the cookie expires much quicker. I've confirmed this behavior on multiple machines with IE and Firefox, leading me to believe it's an IIS7 setting.
Is there a hidden setting that is IIS7 specific related to authentication? All other authentication types are disabled for the website, except for anonymous user tracking.
The authentication cookie is encrypted using the machineKey value from the local web.config or the global machine.config. If no such key is explicitly set, a key will be automatically generated, but it is not persisted to disk – hence, it will change whenever the application is restarted or "recycled" due to inactivity, and a new key will be created on the next hit.
Resolving the problem is as easy as adding a <machineKey> configuration section to web.config, or possibly (preferably?) to the machine.config on the server (untested):
<system.web>
...
<machineKey
validationKey="..."
decryptionKey="..."
validation="SHA1"
decryption="AES"/>
...
</system.web>
Google generate random machinekey for sites that can generate this section for you. If your application deals with confidential information, you might want to create the keys yourself, though.
My understanding is that cookies are expired by the consuming party - the browser, which means that IIS has no say in this
Set session state configured in IIS as
In Process
Use Cookies
Time out = your required time
Use hosting identity for impersonation
Also set EnableSessionState to true (which is default too)
And most importantly run the app pool in classic mode.
Hope your problem will solve.
First of all i must say that these "guidelines" are generic and not iis-7 exclusive.
In web.config under <system.web>
you either have <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" timeout="130" cookieless="false"/> (which requires the ASP.NET Session State Server service running on localhost)
or <sessionState mode="InProc" timeout="130" cookieless="false"/>.
The main difference is that in InProc that session state data are placed in the application process itself. In the other setting a different service is doing the storage, and you application just polls it to get the required data.
Having used both (as well as sql-server session state mode) the InProc is the least reliable but the fastest. The Sql-server is the most reliable and the slowest and the StateServer mode is somewhere in the middle being unreliable only in the case of a power/system failure. Having said that, i must say that for site with a low request count the performance penalty is negligible.
Now, my experience has shown that InProc is quite unpredictable on its stability; i used to have the same problem with you. I was able to extend the stability of the application by tweaking the settings of the application pool, i removed the problem altogether by switching to SessionState (which also allows to bring down the application and not lose session state data).
The reasons that you may suffer from application/session stability:
IIS and application pooling. Each virtul directory of a website is assigned to an application pool (by default to "DefaultAppPool") which has a series of settings amongst which you define the interval that the process is "recycled" - and as such preserve system resources. If you don't change the settings the application may trigger one of the criteria for the process recycler, which means that your application is busted
Antivirus.
In a ASP.NET application if the web.config (and any child .config files the application depends on) file is touched the application is restarted. Now there are cases where an antivirus program may touch the web.config file (say once a day?) and as such the application is restarted and session data is lost.
Bad configuration
Specifically for Forms Authentication the time-related settings and behavior always where dependent on the web-session with the auth-session being under the web-session.
What i don't know is if the Forms Authentication module depends only on Session domain or if it also places data in the application domain as well. If the second is the case then you may have to disable all recycling settings in the Application Pool as well as checking again configuration/antivirus and who stores the session data.
I recently had the same problem where my site was timing out every 20 minutes even though I set the session timeout to 2 hours. I found that it was because IIS worker process was timing out every 20 minutes: http://technet.microsoft.com/en-us/library/cc783089(WS.10).aspx

Resources