c#如何从preinit设置和使用会话状态

好的,这样就可以设置和读取当前会话中的变量

String Myvar =(string) System.Web.HttpContext.Current.Session[“MyVariable”] 

设置

 System.Web.HttpContext.Current.Session[“MyVariable”] = “NewValue” 

我什么都不能,我得到一个System.NullReferenceException: Object reference not set to an instance of an object. 来自System.Web.HttpContext.Current.Session。

在我的web.config中我有

   

我已经阅读了十几篇关于IHttpHandlerIRequiresSessionState接口的必要性的文章。 我认为问题可能是因为我在Page_PreInit请求此信息。 我在堆栈溢出文章中找到了一个解决方案 ,但我似乎没有正确使用它来实际实现这一目标。

我不确定我错过了什么。 提前致谢。

正如评论所提到的那样,在PreInit事件中你是否需要这个?

PreInit在页面生命周期的早期发生。 事实上,在所有控件完全初始化之前,甚至在应用母版页(如果有的话)之前都会发生这种情况。

对于大多数应用程序来说,更好的选择是在Load事件中。 如果你仍然在那里得到NullReferenceException ,那么还有一个更大的问题。

您可以通过在类中实现IRequiresSessionState接口来访问会话。

这是一个标志接口,因此您不需要实现任何额外的代码。

当你实现这个asp.net将知道你想要访问会话。

 public partial class YOUR_ASPX: System.Web.UI.Page , IRequiresSessionState { ... your code } 

要在pre-init之前访问会话状态,您可以执行类似的操作。 我使用它,以便我可以拥有与普通用户不同的管理主人。 每个页面顶部都有一个方法。

 PageTools tools = new PageTools(); protected void Page_PreInit(object sender, EventArgs e) { tools.setMasterPage(Page, Context); } 

PageTools是我的类,它包含选择适当的mater页面并具有http处理程序的方法。

 public void setMasterPage(Page page, HttpContext context) /*********************************************************************** * Author Daniel Tweddell * Date 9/18/09 * * Several of the pages are for non-admin use, however these pages will * also be used by the admin users and will need to have the admin menu * and such. So based on the login, we either show the page with the * standard master or if the user is admin, use the admin master. ***********************************************************************/ { if (context.Handler is IReadOnlySessionState || context.Handler is IRequiresSessionState) { context.Handler = Handler(); } String sMasterPage="~/content/page.master"; if (userinfo.IsUserAdmin) sMasterPage="~/content/administrator/admin.master";//make sure the user is admin page.MasterPageFile = sMasterPage; } 

是设置httphandler的一步一步。 (这是你需要的另一件事。