0

What is the proper way to work with session variables in ASP.NET MVC (mvc 4)

I have something like

  public class SessionData
  {

        const string AccountId_KEY = "AccountId";

        public static string AccountId
        {
            get { return HttpContext.Current.Session[AccountId_KEY] != null ? HttpContext.Current.Session[AccountId_KEY].ToString() : String.Empty; }
            set { HttpContext.Current.Session[AccountId_KEY] = value; }
        }
   }

Then in controllers/views use

SessionData.AccountId = value;

or

 var accId = SessionData.AccountId;

This works sort of... but more often than not, when accessing (get) on the session variable it ends up being null....

This problem has been frustrating as its intermittent. Seems to occur more frequently on the local environment than on the test/live machines.

I have included in the web.config

<modules>
..
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
    </modules> 

And still having issues.

I have set <sessionState timeout="2880"></sessionState>

I just want to be able to get and set session variables nicely ideally with some sort of strong typing... please tell me what is the proper way.

I've come across this...HttpContext.Current.Session is null in MVC 3 application

but think that has made me more confused. A nice end to end example would be awesome!

Community
  • 1
  • 1
raklos
  • 28,027
  • 60
  • 183
  • 301

2 Answers2

0

If you want a basic means of using session variables, use:

Session["AccountId"] = your_value;

then, when you need to reference your session variable in a view:

@Session["AccountId"]

or in an action:

Session["AccountId"]
Eckert
  • 690
  • 4
  • 9
0

The most important thing to know about sessions is that they are volatile. You can never assume that the session will exist because it can honestly go away at any point. Even if you set the timeout high, an in-proc session will expire any time the app pool recycles, the server/IIS restarts, etc.

In development, the situation is worse because by default IIS Express actually shutsdown completely every time you stop debugging. So, if you're debugging, setting a session variable, then stopping to make a change, before starting debugging again, you're wasting your time. The session was destroyed in that process.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444