从System.Web.UI.Page继承时,会话为空

3
我希望扩展System.Web.UI.Page类以添加一些额外的内容。在构造函数中,我需要一个会话变量的值。
问题是Session对象为空...
public class ExtendedPage : System.Web.UI.Page {
   protected foo;   

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

如果我将带有会话对象的部分移到Load事件中,一切都能正常工作...
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"];
   }
}

为什么第一个情况下会出现 Session 对象null的情况?
2个回答

5

你的意思是它不是在构造函数中设置,而是在页面加载之前设置吗?(我认为是在 pre-init 中。) - Steven Sudit

0

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

它在 HttpContext 中运行时将具有 Session。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接