2010-06-16 71 views
3

我想用一些额外的东西来扩展System.Web.UI.Page-class。 在ctor中,我需要会话变量的值。从System.Web.UI继承时会话为空

的问题是,会话对象为空...

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

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

如果我与会话对象到负载事件的一切移动的部分工作正常...

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"]; 
    } 
}

为什么会话对象 null在第一种情况下?

回答

5

在构造Page对象后,Session属性稍后在Page lifecycle中设置。

+0

您的意思是它没有在构造时设置,而是在页面加载之前设置? (我认为在初始阶段。) – 2010-06-16 14:45:43

+1

@Steven:的确如此。 – SLaks 2010-06-16 14:48:03

0

您必须在.aspx页面中继承ExtendedPage类。

在HttpContext中运行时会有会话

+0

如果Load事件正在触发,他已经这么做了。 – SLaks 2010-06-16 14:44:53