9

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?

5
  • Try to search on StackOverflow, there are a lot of the same questions with many advices
    – sll
    Aug 5, 2011 at 15:31
  • Do you run both web servers behind a load balancer? (and are you sure you've had a good check through your code for where these are set to be sure they're not overwritten)?
    – Paddy
    Aug 5, 2011 at 15:31
  • I have been through the code repeatedly looking for where I may be inadvertently overwriting them, but cant find any place that I am. Also, it happens on many different pages for different session vars - and with different users/browsers/platforms. I cant find any correlation between instances when this happens
    – Stephen
    Aug 5, 2011 at 15:45
  • 1
    Might be worth double-checking that you don't have any empty catch blocks. If you try to add to the session an object which isn't Serializable (or one which contains a nested object that isn't serializable), it will throw. But if you're catching & eating that thrown exception, you could end up in a situation where you thought you added something to the session, but it failed quietly.
    – mikemanne
    Aug 5, 2011 at 16:10
  • @mikemanne - Thats a good thought, and I will definitely be checking for NonSerializable objects if/when I implement a State Server, but since its currently InProc, I can add any object to Session, not only Serializable objects. That's been one of the reasons I havent yet done the State Server - there are so many places to go through and make sure all objects are Serializable..
    – Stephen
    Aug 5, 2011 at 16:16

6 Answers 6

7

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

6
  • This was my first thought as well. However, since he said "When particular Session variables are lost, most of the other Session variables for the same user are still in place.", I'm less likely to suspect session-affinity failure.
    – mikemanne
    Aug 5, 2011 at 15:34
  • 1
    that can happen. maybe the user was on the server 1(let's say few session variable were created) then if the request is served by the server 2 and the code try to access to a session variable which doesn't exist on that server it will get a null reference Aug 5, 2011 at 15:38
  • sorry, I should've specified that too.. only 1 server, not a server farm
    – Stephen
    Aug 5, 2011 at 15:41
  • I have seen the ScottGu page before. I used some of his code to handle the app pool shutdown logging - I have updated the original post with that code. The thing is, I dont think that is happening at all.. everyone else online stays active and doesnt lose any session values. plus the user that it happens to stays active (their user info is in session) and they have other values in session that are unaffected.
    – Stephen
    Aug 5, 2011 at 16:01
  • try also to use the Health Monitoring Events showed on the last link at the paragraph "How do you determine what caused an appdomain restart?" Aug 5, 2011 at 16:04
7

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

3
  • 1
    having a similar problem, issue is hard to replicate... (other users do not, and i dont think a browser can cause this, as browser job is to send the sesisonid only). But above is a logical reason, we will explore if user open multiple pages.
    – visual
    Apr 8, 2013 at 8:25
  • Avoid this multiple-page issue by using a better design. Remove all client-state from your session variables and put them on the querystring instead... ie. ?reportname=summary&page=1&pagelength=20&reportparameter1=etc My opinion is that the Session is only useful for storing the userid or hash, when they login or return with a cookie.
    – Awerealis
    Dec 5, 2013 at 23:14
  • @Awerealis, yes, passing params in the querystring is indeed one option if you have only a few params. Unfortunately, there is a lot going on on my pages, and I am already using the scriptManager history state which loads up the url with hash values: <asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true" EnableSecureHistoryState="false"> Due to the large number of history state params, I had to increase the httpRuntime maxURLLength b/c 260 wasnt long enough. Not to mention the fact that there are plenty of things in session that we dont want/need to expose to the client.
    – Stephen
    Dec 6, 2013 at 21:30
1

The session issues you are facing can happen because of multiple reasons

  1. 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.

  2. 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.

  3. Process restarts: w3p process of your website is getting restarted because of some issue in code. or memory leaks.

1

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"/>
1

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).

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.