I've been searching for answers for quite some time on this as it continues to plague me. We store user login info and other data about the user's current activities in Session State (InProc). Every so often I get a Null Reference exception trying to use one of the session variables. It happens on random pages, with random Session variables. I have modified the web.config httpRuntime and compliation tags to prevent appPool restarts:
<httpRuntime requestValidationMode="2.0" waitChangeNotification="86400" maxWaitChangeNotification="86400" />
<compilation debug="False" strict="false" explicit="true" targetFramework="4.0" numRecompilesBeforeAppRestart="1000" />
I have set IIS to restart the app pool at 3am to make sure it doesnt restart when people are busy using the server. And I'm logging app pool restarts in the event log to make sure I know when its happening.
Dim runtime As HttpRuntime = GetType(System.Web.HttpRuntime).InvokeMember("_theRuntime", BindingFlags.NonPublic Or BindingFlags.Static Or BindingFlags.GetField, Nothing, Nothing, Nothing)
Dim shutDownMessage As String = runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, runtime, Nothing)
Dim shutDownStack As String = runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, runtime, Nothing)
Dim evtSource As String = "ASP.NET"
Dim log As New EventLog
log.Source = evtSource
log.WriteEntry(String.Format("_shutDownMessage={0}{2}_shutDownStack={1}", shutDownMessage, shutDownStack, vbCrLf & vbCrLf), EventLogEntryType.Warning)
I get the event log entries when the app pool restarts.
The App Pool is NOT restarting when these errors happen.
When particular Session variables are lost, most of the other Session variables for the same user are still in place. Also, there are typically another 10-20 users logged into the site that are unaffected when it happens.
The user that gets the error will back up, go through the same pages again, and it will work fine.
I was having this problem on a Windows Server 2003 (32bit) running IIS6 with .NET 3.5 32bit and 4GB of memory.. As part of our server upgrades about a year ago we got a new webserver - Windows Server 2008 (64bit) running IIS 7 with 16GB memory. I upgraded the website to .NET 4.0 64bit. Still having the same problems on the new machine (usually 1-3 times per day - at random times through the day).
I cant make it happen in my debugging due to its random nature, but I do believe it happens randomly on our dev environment as well. The dev server has virtually the same specs as the production one.
Both environments are isolated and running as a single web server, not a part of a web farm.
I'm thinking that I may try to implement a State Server to get out of the InProc mode, but that's just another stab in the dark..
Other than trying the State Server, is there anything else I can do to identify when this happens or prevent it?
if your web app deployed on a server farm (more then one server web)
As you said you are using an InProc session and it may happen the user is redirect to a different server from the one where it is has been stored that session variable.
In this case you should go for an out of proc session as you have mentioned(Session State Server)
if you go for a State Server bear in mind the below just to prevent any other issue:
Since the Stateserver combines the ASP.NET Session ID with the IIS
application path to create a unique key, sessions issued for one of
the five new webs could not be found when accessed through one of the
other webs which is obviously extremely unfortunate in a weighted
round robin load balanced web farm
http://www-jo.se/f.pfleger/session-lost
have also a look at this logger to understand if the app recycle against your will:
http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx
http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx
For anyone that is interested, or dealing with similar issues, I wanted to follow up with the cause of my problem here.
I implemented NCache out-of-process state server for Application Cache and Session State about 7 or 8 months ago. Unfortunately, moving the session out-of-process has not had any impact of my problem of losing random session variables during report selection on my site. And, as I had been unable to replicate this problem, I had not put more effort into trying to fix it until recently when another problem made the light go off in my head.
To get to the point - I was not overwriting the session variables somewhere that I didnt realize, but the problem was the user was opening up a second (or third) tab to compare report selection options side by side. We have several custom reports where the user can select multiple options to generate custom reports (think of it like a wizard control where there are several steps to create a custom report). If a user is on step 3 of 5, and then opens a new tab and starts going through the report selection process again, the new selections are overwriting the old selections b/c the 2 tabs shared the same session. I verified this was the case by opening multiple tabs and stepping through the selection process.
I am in the process of trying to distinguish between multiple report runs so that the selections for one report are stored using a unique session key from other report selections. That is proving difficult as well, but is not really related to the problem I thought I was having with missing session data.
If anyone finds this post and thinks they are losing session data randomly and cant replicate it, try debugging your site and opening multiple tabs. Stepping through both tabs at the same time illuminated the problem for me.
HTH
The session issues you are facing can happen because of multiple reasons
Session expiration : as you are using Inproc mode, sessions are
valid only for the sessiontimeout timeperiod. which is 20 mins by
default. try to use sessionstate tag in system.web section of your
web .config and set timeout value to a larger value.
Another Issue could be because of webfarms and web gardens. if
you have configured web farms and web garden for your web site.
Inproc session sharing can cause issues.
Process restarts: w3p process of your website is getting
restarted because of some issue in code. or memory leaks.
I ran into this problem because our server was setup to run https. The sessions would not be retained if I ran under simple http. However, the sessions were retained when running on https. So we setup a URL rewrite rule to always send the application to https if they came in via http.
In addition sessions will not work locally or on the server unless you are running https (note the S on the end of https), if you have the following in your web.config file:
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
Since it took me a while to figure this one out, I thought I'd post this here in case it helps someone else too.
I ran into a situation where both IE and Chrome were randomly dropping session variables too. I searched and searched and everyone said the usual things...check domain name, check your IIS settings for cookies...etc.
My issue turned out to be a permissions thing.
In my web.config, I have a permission entry for a 'public' folder that can be accessed by the unauthenticated public.
<location path="public">
<system.web>
<authorization>
<allow users="*" />
<allow users="?" />
</authorization>
</system.web>
The problem was a public-side .js call to a HttpHandler that was NOT on the public side.
In an attempt to reuse code, I pointed both the secure and public side to code in the secure side. I guess as a side effect, it killed the session, without a very meaningful error message.
I may add another entry just for that handler, or I may make a public and a secure copy of that code (a less desired approach).
One more condition is there where sessions can loose its value.
You can use Fiddler tool to trace out this problem.
The most condition can be found when you some element like source not found in solution. At that moment server will try to reload that unfounded or lost object by restarting the project. Restarting the project will resulted into resetting all session objects.
Thanks.
Related
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.
I wrote a test page that does a bunch of busy work in a method called at page load. This process as I have it now takes around 12 seconds.
If I try to load another page while the first long running page is loading, this second page doing nothing except writing out a hello world, it doesn't load until the first long running page is finished.
Why is this the case? I would think IIS would be able to handle multiple concurrent connections, it seems crazy that one long running page would stop every other page in the application from loading. I must be missing something or not understand how IIS works.
I would think multiple independent requests would be spawned on different threads. Is this only the case if the requests are from different sessions entirely? Are all requests from a single session bound to a single thread?
bd
You need to turn off sessionState... if session is on, any sub-sequent request is waiting on the previous thread to finish in order to continue on that particular session.
So turn session off, it will not need to wait for any previous session.
in web.config put
<system.web>
<sessionState mode="Off" />
</system.web>
Now you should have those request process concurrently.
I just hit this issue too, and for me it turns out it is the session feature of ASP.NET. Basically if you have sessions enabled, each request will return in the order it arrived per user.
Try using 2 different browsers, for me it no longer blocked. Here is a similar question:
IIS 5.1 on XP Classic ASP appears to be in single threaded mode
It's a threading problem. While IIS can handle multiple connections simultaneously, ASP.NET, by default, is configured in single-threaded mode.
This choice by Microsoft was to prevent dummy developers to make common concurrency mistakes. ASP.NET for Mono doesn't show this behaviour and if you access shared resources without prior locking you might be... f... you know ;) by a yellow page of death.
I don't remember the exact procedure, but in the properties of your website you can choose the application pool and also the number of threads. I saw with my eyes that IIS6 sets it to 1 by default.
If you can't find it, tell me and tomorrow I'll take a look on my development server in lab.
Hope to have been of help.
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.
I'm having a problem with a web app I'm managing. Users starting receiving the following error occasionally:
Validation of viewstate MAC failed. If
this application is hosted by a Web
Farm or cluster, ensure that
configuration specifies
the same validationKey and validation
algorithm. AutoGenerate cannot be used
in a cluster.
The problem is that it's not a cluster - it's a single Windows 2003 server. After digging around, it appears that adding a machineKey section and some extra attributes to the Pages directive in my web.config resolves this error:
<machineKey validationKey='MACHINE KEY SNIPPED'
decryptionKey='DECRYPTION KEY SNIPPED'
validation='SHA1'/>
<pages validateRequest="true" enableEventValidation="false">
After changing these two things in my web.config, the error goes away, but now I have a new problem - Instead of an error that my viewstate is invalid, the app just "Forgets" who my user is, and sends them back to the login page. Now, the users are browsing through the application, and then they're unexpectedly sent to the login page, even after they've already been logged in for a few minutes. While I can't force this to happen, it usually happens within visiting 10-12 different pages, so pretty frequently.
I'd love a resolution to this - does anybody know what else might be causing the viewstate error on a single server, or what I can do to ensure that it's validated properly?
It sounds as though the worker process is recycling itself (assuming you're storing session state in-process). Picking a fixed key means that the viewstate is still valid when the process comes back up, but you've lost the session state. You could try storing the session state in a database, but I'd be more concerned to fix the underlying problem. Does your application suddenly allocate vast amounts of memory, or anything like that? Is there anything suspicious in the event log?
It turned out that this began happening when I added additional worked processes to the app pool that was running our application. Because the session state was being stored InProc (and not in a state service or a SQL Server), it was losing track of who the user was when it switched them between working processes. For now, dropping the number of processes on our server back to one corrected the problem, since raising it didn't seem to have any improvement in the first place.
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.