Losing my session variables

点点圈 提交于 2020-01-15 03:43:12

问题


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


回答1:


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.




回答2:


In proc session state gets cleared out pretty commonly. For example, if your app doesn't get any requests for a while, IIS will by default shut it down (losing any inproc session state) until a request comes in. If you need session state to persist, look into hooking another provider such as the SQL one. More here: http://msdn.microsoft.com/en-us/library/aa479041.aspx#aspnetsessionstate_topic6




回答3:


One thing to check is if you are clearing session variables or re-creating session variables at any point in your web application. If so, missing session variables could be caused by the user clicking back navigation in their browser, clearing session state, and then forward navigation in their browser, when your app looks for the now deleted variable.




回答4:


I hope this helps someone Losing Session State as it helped me. In my case it was generation of files that was making it to loose the session state. Moving file generation logic to a simple console app helped.



来源:https://stackoverflow.com/questions/8331793/losing-my-session-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!