views:

45

answers:

2

I want to extend the System.Web.UI.Page-class with some extra stuff. In the ctor I need the value of a session-variable.

The problem is that the Session-object is null...

public class ExtendedPage : System.Web.UI.Page {
   protected foo;   

   public ExtendedPage() {
      this.foo = (int)HttpContext.Current.Session["foo"];   // NullReferenceException
   }
}

If I move the part with the session-object into the Load-Event everything works fine...

public class ExtendedPage : System.Web.UI.Page {
   protected foo;

   public ExtendedPage() {
      this.Load += new EventHandler(ExtendedPage_Load);
   }

   void ExtendedPage_Load(object sender, EventArgs e) {
      this.foo = (int)HttpContext.Current.Session["foo"];
   }
}

Why is the Session-object null in the first case??

+5  A: 

The Session property is set later in the Page lifecycle, after the Page object is constructed.

SLaks
Do you mean that it's not set at construction but is set before page load? (I think in pre-init.)
Steven Sudit
@Steven: Exactly.
SLaks
A: 

You have to inherit the ExtendedPage class in an .aspx Page.

It will have Session when run in the HttpContext

Ed B
If the `Load` event is firing, he's already doing that.
SLaks