Losing session variables with ASP.NET.

I was working on my MVC4 application with C#.NET framework 4.0 and I couldn’t hold a variable in a session. Why not?

Short answer: Never put a file you need to access from your web application in your ‘bin’ folder.

This question led me on quite a journey let me tell you. There are a vast multitude of answers possible to this question, so I will focus in this post on my own personal journey. Your session mode is very important, make sure you familiarize yourself with the different modes (http://msdn.microsoft.com/en-us/library/ms178586.aspx). I had it on the default mode which is InProc.

InProc can be dangerous in an operational environment because your session is stored in memory on the local webserver.

The memory associated with your web application is controlled by the AppDomain which is fired up when the first resource (such as a page) in an ASP.NET application is requested from the webserver. This AppDomain can be restarted for several reasons, here’s a list (and quite a nice extensive case study on the subject by Tess Ferrandez): http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx

Have you read: “Why does an application domain recycle”? Look at bullet point number 2: “The bin directory or it’s content is modified”. The FCM (File Change monitor) appears to be quite jumpy, because all I have to do is access my XML file in the bin directory and the application domain is recycled, which causes the session to be born anew, which causes my session var to be non-existent (read: null).

If you have a situation like mine, put your XML file in the App_Data folder (where it belongs to be honest) and it’ll all run smoothly.


About Danny

Bachelor in Commercial ICT MCTS Winforms .NET 2.0 MCTS ASP.NET 3.5 PSM I
This entry was posted in .NET programming, ASP.NET MVC and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s