I am using following code for session management.
public class MyClass
{
public static int SomeProperty
{
get { return (int)HttpContext.Current.Session["MyID"]; }
set { HttpContext.Current.Session["MyID"] = value; }
}
}
Problem is once in a while I get “Object reference not set to an instance of an object.” on get { return (int)HttpContext.Current.Session["MyID"]; }, although I know for fact that MyID was been set in session. Seem to me that for some reason that session is destroyed. Any ideas why that can happen?
I have nothing defined for session state in web.config which leads me to believe that this is a case of InProc server
InProc session state is subject to appDomain recycles. Every time you change the site’s code or config, this can happen. IIS can also automatically recycle it from time to time, too.
You must always assume it could be null, and handle it accordingly.