ASP.NET Why are sessions timing out, sessionstate timeout set - asp.net

Hey I have the following line in my web.config
<sessionState mode="InProc" timeout="45"/>
Which I thought would keep sessions intact for 45 mins
But I have seen the case where if a user is inactive for lets say 15 mins the sessions times out.
How can I stop this ?
Edit : Just noticed I have the following line in the master page
meta http-equiv="Refresh" content="1800;URL=http://www.virtualacademy.ie/login.aspx">
Maybe this is causing the issue, what is the above line doing i.e the number 1800

Be sure to check your IIS configuration because the application pool that your site is hosted on also has its own timeout value which will override your own .config.
To increase it,
Open IIS
Select Application Pools on the left side
Select the Application Pool used by your site
Choose advanced settings
Under Process Model categtory increase the 'Idle Time-out' value to the desired length.
Hope this helps.
(If you do not have a dedicated server / access to IIS with your hosting provider you will have to contact them to see if they can increase it for you)

If the user closes their browser or clears cookies, or if the AppDomain on the server is recycled, the session state will be lost.
Have you checked logs to see if the app is recycling?

AppDomain recycles are a very common problem for this if the sessionState is InProc. It is very much advised to use a StateServer or SQLServer for production systems instead. See Session-State Modes for documentation on how to use each, and the pros and cons of the three different types.
Personally, we use SQL Server if we must for web server farms--slower but can be shared. We use State Server if the site will only be hosted on a single web server--state survives AppDomain restarts, but not entire server restarts.
Also, in the past we have used an AJAX post in the background while the user is watching long running videos or performing long client-side tasks, so that the session timeout gets reset every few minutes. Nothing special about this code--just have a little JavaScript hit every few minutes some ASPX page that returns nothing.

Are you using Forms Authentication? It has its own timeout setting that when expires will redirect the user to your login page even if their session is still valid.

Related

Asp.net Application State expiration

I suppose that application state and session state are two different things.
If I can set expiration time to session state, can I do same to an application state in my web.config ?
I just want to prevent my application from rebuilding after 5 minutes.
I don't know exactly what happens. When accessing the website for the first time, the site takes 10 seconds to appear. If I return to the site before 5 minutes, the site appears immediately. If there are more than 5 minutes of inactivity, when I access the site again, the site takes 10 seconds. I guess it was the application state Who expired ?
The easiest way I know of to keep your site alive is to make sure traffic is always coming through. If you have access to a scheduled job runner, have it ping a dummy aspx page every minute or two - this way, your app should run indefinitely.
If not, there are techniques to cheat the system. You can have a cache item built, and upon expiration of that cache item, create another cache item. This will perpetually keep running code every X minutes, which will keep the app alive. The problem with this is that if the app ever does die (server reboot, IIS restart, etc.), the app will be dead until someone makes a real request, at which point it will stay alive indefinitely again.
This technique is sometimes used to simulate a task scheduler in ASP.NET. Just keep in mind that it's not perfect.
EDIT: For clarification, you wouldn't just create a new cache item, you'd actually make a request to a page which would then in turn create the cache item. This ensures that another request is made through IIS, which in turn runs the full lifecycle, keeping the app alive.
Even if you do set your session timeout high, there's no guarantee that it will hold. I've dealt with hosting companies who will recycle your application pool after just a couple minutes of inactivity, killing any sessions you may have open. They don't care that you may have sessions open - they are just trying to squeeze every CPU cycle they can out of their servers. So if you're on shared hosting, you may want to keep that in mind - you may not be able to control how often they kill your app.
Application State starts when the first session is created, and is automatically ended after the last session expires. As long as you have continued access to the website, the application will remain active.
I don't know what you mean by having application "rebuild". Changing any file related (i.e. file with compilable code) will cause the application to either recompile (if you have a web directory) or reload (if you have a web application). This action will always end all sessions and end the application.
Not sure it is still actual.
The problem doesn't linked with SessionState or ApplicationState.
To avoid slow reaction of your web-site you have to activate AlwaysRunning mode of your IIS
To do that add to your web.config the next
<applicationPools>
<add name="MyAppWorkerProcess" startMode="AlwaysRunning" />
</applicationPools>
You can configure your session state in your configuration file for preventing this expiration.
For example:
<sessionState
mode="SQLServer"
sqlConnectionString="data source=127.0.0.1;user id=<username>;password=<strongpassword>"
cookieless="false"
timeout="20"
/>

Increasing Session TimeOut

Site hosted via IIS 7.0
I would like to set my session time-out to 9 hours in my ASP.NET application.
This has been set at web.config
<sessionState timeout="540"></sessionState>
But, as I understand, if the timeout is set as 20 minutes inside the IIS where the website is hosted, setting an extended session state will be of no use.
Firstly, I would like to confirm whether this assumption is right.
The problem is that I do not have access to the IIS of my shared hosted web server.
Now, after some research, I came up with another solution in code project. This sounds like a wonderful idea. The idea is to insert an iframe to master page. The iframe will contain another page with meta refresh less than 20 minutes.
Response.AddHeader("Refresh", "20");
This idea seemed good for me. But the article is 7 years old. Plus at comments section a user complaints that this won't work if the page is minimized and I am worried that the same happens when my pages tab is not active.
I would like to know these things
Whether the refresh method will work for my scenario , even if the page is minimized?
Are there any other methods that could increase session time out that overrides IIS timeout setting?
Also I read some questions in Stack Overflow where the answers state that the IIS session timeout is for clasic ASP pages. Then why is not my extended timeout not firing?
Firstly, I would like to confirm whether this assumption is right.
Yes, this assumption is absolutely right in case you are using in-memory session state mode. In this case the session is stored in memory and since IIS could tear down the AppDomain under different circumstances (period of inactivity, CPU/memory tresholds are reached, ...) the session data will be lost. You could use an out-of-process session state mode. Either StateServer or SQLServer. In the first case the session is stored in the memory of a special dedicated machine running the aspstate Windows service and in the second case it is a dedicated SQL Server. The SQL Server is the most robust but obviously the slowest.
1) Whether the refresh method will work for my scenario , even if the page is minimized?
The hidden iframe still works to maintain the session alive but as I said previously there might be some conditions when IIS unloads the application anyway (CPU/memory tresholds are reached => you could configure this in IIS as well).
2) Are there any other methods that could increase session time out that overrides IIS timeout setting?
The previous method doesn't increase the session timeout. It simply maintains the session alive by sending HTTP requests to the server at regular intervals to prevent IIS from bringing the AppDomain down.
3) Also I read some questions in Stack Overflow where the answers state
that the IIS session timeout is for clasic ASP pages. Then why is not
my extended timeout not firing?
There is no such thing as IIS session timeout. The session is an ASP.NET artifact. IIS is a web server that doesn't know anything about sessions.
Personally I don't use sessions in my applications. I simply disable them:
<sessionState mode="Off"></sessionState>
and use standard HTTP artifacts such as cookies, query string parameters, ... to maintain state. I prefer to persist information in my backend and retrieving it later using unique ids instead of relying on sessions.

Losing Session State

I have an ASP.net application where Users aren't able to successfully complete certain actions, for reasons, I'm assuming, can only be related to losing their session (which is where I maintain their current user information, and how determine whether they are logged in)
I'm at a loss as to why they would lose their session, so my first question is:
What (in general) would cause a user to lose their session in ASP.net?
and since I don't know when a user loses their session and can't reproduce it myself:
How can I track when I user loses their session
Below is my sessionState config for reference
<sessionState
mode="InProc"
cookieless="false"
cookieName="My.Site.Com"
timeout="480"/>
A number of things can cause session state to mysteriously disappear.
Your sessionState timeout has expired
You update your web.config or other file type that causes your AppDomain to recycle
Your AppPool in IIS recycles
You update your site with a lot of files, and ASP.NET proactively destroys your AppDomain to recompile and preserve memory.
-
If you are using IIS 7 or 7.5, here are a few things to look for:
By default, IIS sets AppPools to turn themselves off after a period of inactivity.
By default, IIS sets AppPools to recycle every 1740 minutes (obviously depending on your root configuration, but that's the default)
In IIS, check out the "Advanced Settings" of your AppPool. In there is a property called "Idle Time-out". Set that to zero or to a higher number than the default (20).
In IIS, check the "Recycling" settings of your AppPool. Here you can enable or disable your AppPool from recycling. The 2nd page of the wizard is a way to log to the Event Log each type of AppPool shut down.
If you are using IIS 6, the same settings apply (for the most part but with different ways of getting to them), however getting them to log the recycles is more of a pain. Here is a link to a way to get IIS 6 to log AppPool recycle events:
http://web.archive.org/web/20100803114054/http://surrealization.com/sample-code/getnotifiedwhenapppoolrecycles/
-
If you are updating files on your web app, you should expect all session to be lost. That's just the nature of the beast. However, you might not expect it to happen multiple times. If you update 15 or more files (aspx, dll, etc), there is a likelyhood that you will have multiple restarts over a period of time as these pages are recompiled by users accessing the site. See these two links:
http://support.microsoft.com/kb/319947
http://msdn.microsoft.com/en-us/library/system.web.configuration.compilationsection.numrecompilesbeforeapprestart.aspx
Setting the numCompilesBeforeAppRestart to a higher number (or manually bouncing your AppPool) will eliminate this issue.
-
You can always handle Application_SessionStart and Application_SessionEnd to be notified when a session is created or ended. The HttpSessionState class also has an IsNewSession property you can check on any page request to determine if a new session is created for the active user.
-
Finally, if it's possible in your circumstance, I have used the SQL Server session mode with good success. It's not recommended if you are storing a large amount of data in it (every request loads and saves the full amount of data from SQL Server) and it can be a pain if you are putting custom objects in it (as they have to be serializable), but it has helped me in a shared hosting scenario where I couldn't configure my AppPool to not recycle couple hours. In my case, I stored limited information and it had no adverse performance effect. Add to this the fact that an existing user will reuse their SessionID by default and my users never noticed the fact that their in-memory Session was dropped by an AppPool recycle because all their state was stored in SQL Server.
I was having a situation in ASP.NET 4.0 where my session would be reset on every page request (and my SESSION_START code would run on each page request). This didn't happen to every user for every session, but it usually happened, and when it did, it would happen on each page request.
My web.config sessionState tag had the same setting as the one mentioned above.
cookieless="false"
When I changed it to the following...
cookieless="UseCookies"
... the problem seemed to go away. Apparently true|false were old choices from ASP.NET 1. Starting in ASP.Net 2.0, the enumerated choices started being available. I guess these options were deprecated. The "false" value has never presented a problem in the past - I've only noticed in on ASP.NET 4.0. I don't know if something has changed in 4.0 that no longer supports it correctly.
Also, I just found this out not long ago. Since the problem was intermittent before, I suppose I could still encounter it, but so far it's working with this new setting.
In my case setting AppPool->AdvancedSettings->Maximum Worker Proccesses to 1 helped.
Your session is lost becoz....
JUST MAKE SURE THERE ARE NO RUNTIME ERRORS, ANY FATAL EXCEPTION WOULD
KILL THE SESSION!
In Microsoft stack, Visual Studio - put Ctrl + Alt + E - All Exceptions ON, then run the code in Debugging mode. Any Fatal ones are THE reason for session loss..
You could add some logging to the Global.asax in Session_Start and Application_Start to track what's going on with the user's Session and the Application as a whole.
Also, watch out of you're running in Web Farm mode (multiple IIS threads defined in the application pool) or load balancing because the user can end up hitting a different server that does not have the same memory. If this is the case, you can switch the Session mode to SQL Server.
I was only losing the session which was not a string or integer but a datarow.
Putting the data in a serializable object and saving that into the session worked for me.
Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses was set to 2 and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.
Solution was to Change MaximumWorkerProcesses to 0 in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses.
Dont know is it related to your problem or not BUT Windows 2008 Server R2 or SP2 has changed its IIS settings, which leads to issue in session persistence. By default, it manages separate session variable for HTTP and HTTPS. When variables are set in HTTPS, these will be available only on HTTPS pages whenever switched.
To solve the issue, there is IIS setting. In IIS Manager, open up the ASP properties, expand Session Properties, and change
New ID On Secure Connection to False.
I had same problem by losing sessions. every time , every page reload, my sessions clear and by new reload any page, my sessions returned by valid value...
i fixed it by change MaximumWorkerProcesses from 0 to 1 in iis
I was struggling with this issue for 14 days.
Here's what helped me:
Check your recycling options in App Pool > Advanced settings. Turn off all of the options so it won't recycle on its own.
Check your web.config file for the executionTimeout property under httpRuntime and increase its value.
Check your web.config file for the timeout property under sessionState and increase its value (I set it to 300 minutes).
Go to the server's event log and check the Application log for unhandled exceptions that may cause the worker process to crash. Fix them in your code or use try and catch to eliminate this crash.
Try changing the value of your maximum worker process from 0 to 1 or the other way around, this may also solve this issue.
In my case, session state was loosing due to Load Balancer. Session was storing in one server and Load balancer was redirecting next call to another server where session state was missing.

ASP.NET Application Restarts Too Much

I have an ASP.NET WebSite which restarts in every 1-2 hours in a day so sessions and other thing are gone and users are complaning about it, because they open a page and do something for 20 minutes and when they submit it, a nice "we are sorry" page is there.
I don't do anything which restarts the application (changing the web.config, changing the files, or even other buggy things like deleting a folder in App_Data which normally shouldn't cause a restart).
Can it be related with Server's hardware? It is not much powerful.
I guess this is recycling.
App pools in IIS get recycled by default - either after a timeout, or after "n" hits.
This should be expected, and is part of the normal processing (although it can be disabled in the app-pool configuration; IIS6 | IIS7).
The fact that this breaks your app suggests that you are using a lot of things like in-memory sessions. Consider moving these to database backed implementations. Apart from withstanding both app-pool restarts and server reboots, this can allow you to scale the site to multiple servers.
Check this blog post about some possible causes for appdomain recycles. There are many possible causes.
If you are unable to fix the problem you could switch from in-process session state to eiter a session state server or to storing session state in a database. Both options are easy to set up and works quite well, but there is a performance impact (between 10-20% I think). There is a nice article here about how to setup a session state server.
Sounds like the app is being recycled or process is failing.
Check app pool settings http://msdn.microsoft.com/en-us/library/aa720473(VS.71).aspx
and event viewer.
Since you mention that your server is small, you might check to see if your worker process is consuming more memory that you have set in your processModel in machine.config. That can cause a reset.
Are you sure that the ASP.NET application actually restarts? Or do you think that it happens because of the lost Session and such?
What is your application's (and IIS') Session timeout variable? The default value of the timeout is 20 minutes, so that's why I am asking. You can set the timeout in your web.config as follows:
<system.web>
<sessionState timeout="120"/>
</system.web>
But apart from that, there are also places inside IIS itself where you can set it. In the case of IIS6 those places are:
Properties of a virtual directory > Home Directory (tab) > Configuration (button) > Options (tab) > Session timeout
Properties of a virtual directory > ASP.net (tab) > Authentication (tab) > Cookie timeout
I'm not sure whether or not both are actually needed, but I usually set both to the same value as I set it in my web.config.
Is there any indication of the cause of the restart logged in the Event Log?
Do you have any anti-virus software running on the server. A change to the web.config will cause your application to restart afaik so in some instances anti-virus software passing over the web.config might alter the attributes on the file which could be causing the reset.
Try disable any AV software or exclude the web applications directory from the AV auto scanning.

Why do I lose my Session Variable in 5 minutes?

I have a web page where the user select a Company and with that I keep the Company name in memory though a Session but when I go to the next page the Session only last like 5 minutes?
Any reason why and how I can fix this, I did extend the Session state in the Web.config but that did not work.
Example: Session("CompanyName") = "Bytes Technology"
In my web.config I have:
timeout="40" />
I move from Default.aspx to CompanyDetail.aspx with my Session("CompanyName")
But if I let the program idle in CompanyDetail.aspx I lose the Session State.
Any ideas?
Regards
Etienne
from your comment I see that you think your site is in a load-balancing server farm.
in this case you need to store your session in db or avoid using it: you cannot be sure that the same server will serve the same user each time he does a postback, and if the user goes from server "A" to server "B" in two different posts... your session variables are lost.
try a google search for "sessionstate database", you'll find tons of stuff on this.
hope this helps
andrea
some questions:
the timeout time is always the same? 5 minutes?
is your site running in a load-balancing server farm? with more than one front-end server?
what are you telling in your web.confing regarding sessions and sessionstate?
I'd wager your not using a load-balanced farm, and are actually using shared hosting.
In a load balanced farm, your code is deployed to multiple servers, and if you have sticky sessions disabled, the user will utilize the server with the least load on each request.
Since you are using 3rd party hosting, I heavily doubt you are doing that.
Session timeout can be hardset in IIS by the host provider, and the most likely culprit is that they have set this to 5 minutes.
Call your host provider, ask them what their IIS session settings are, and go from there.
In IIS, go into the properties of your website, click to the Home Directory tab and then click the Configuration button. Here, click the options tab and check the Session timeout there. I'm pretty sure this only effects classic ASP, but I'm not 100% sure.
If this happens always at 5 minutes then check web.config for session settings, and check IIS: website/Properties/ASP.NET, click on Edit Configuration, select State Management tab, and check session settings.
could there be some antivirus on the server that's causing the web app to reset itself every 5 minutes, with the ASP.NET runtime thinking either the binaries or the web.config has changed? that is also possible.
Another idea is to put the machine name into a comment on a page and see if that is changing from page to page just to confirm that there is a changing of the server handling the request.
thank you everyone for all the information. The company hosting my site just extended the time of the application pool and that worked!
Thanks
Etienne
http://www.erate.co.za
I decided to scrap using Session Variables and went with Query Strings!! Much better!!

Resources