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!