locked
Why Cannot Get Access to Session Variables in Constructor? RRS feed

  • Question

  • User1791176437 posted

    I find that if I try to get access to any session variable in a class constructor, I will get this error message:

       "Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive"

    I have worked around this problem by restoring session state in Page_Load() event handler instead of in the class constructor.

    Seem to me that the best place to restore session state for a class object is to restore its session variables in the class constructor.  Therefore, I would like to find a way to fix this problem in a way that I can restore session state in the class constructor.  If this can be done, please tell me how.  If this cannot be done, please also let me know and I will stick with doing this in Page_Load().

    By the way, I am using Visual Studio 2003 with .NET 1.1.

    Thanks in advance for any info.

    Jay Chan

    Monday, June 13, 2011 11:39 AM

Answers

All replies

  • User-158764254 posted

    you wont be able to use the constructor.  

    The page goes through a life-cycle and Session state is not made available until part way through that lifecycle when the AcquireRequestState event fires: http://msdn.microsoft.com/en-us/library/0dbhtdck.aspx.

    you can see the life-cycle here: http://forums.asp.net/t/1191194.aspx

    So you'll want to stick with a page lifecycle event such as init or load.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 13, 2011 5:50 PM
  • User1791176437 posted

    Thanks for letting me know that I cannot restore/save session variables in constructor or destructor and must do those things in Page_Load.

    OK, this means I can only do save/restore session variables in classes that have Page_Load, and cannot do this for generic classes that don't have Page_Load event.  The classes that have Page_Load event will have to take care of maintaining session state of classes that don't have Page_Load event.  This is fine with me.

    Jay Chan

    Tuesday, June 14, 2011 10:06 AM