C#ASP.NET会话管理器抛出空引用异常

时间:2016-04-23 22:15:55

标签: c# asp.net session nullreferenceexception

我正在尝试实现一个静态SessionStore类,该类应该充当HttpContext.Current.Session["objSession"]对象的包装器,该对象存储在SessionManager中并实际保存用户的所有会话数据。 SessionStore类具有与SessionManager相同的属性,但需要额外的方法来根据需要操作会话数据。基本上,HttpContext.Current.Session有助于获取/设置存储在会话对象中的属性。

所有类都存储在与Web解决方案相同的命名空间中,并且所有类都是可序列化的。

我尝试了两个不同的问题解决方案,在尝试使用public static class SessionManager { static SessionManager() { if (HttpContext.Current.Session != null) { try { if (HttpContext.Current.Session["objStore"] == null) { HttpContext.Current.Session["objStore"] = new SessionStore(); } } catch (NullReferenceException) { HttpContext.Current.Session["objStore"] = new SessionStore(); } } } 进行任何操作时,都在同一点抛出了空引用异常:

protected void Page_Load(object sender, EventArgs e)
        {

            if (SessionManager.groupSettings.Count > 0)
            {
                pnlDashboard.Visible = true;
                pnlLogin.Visible = false;
                getDisplayData();
            }
            else
            {
                pnlDashboard.Visible = false;
                pnlLogin.Visible = true;
            }
        }

调用页面的代码隐藏:

SessionManager

调试器一直步入if (HttpContext.Current.Session != null)一直到行

HttpContext.Current.Session

然后停止并抛出异常。但是,当我将鼠标悬停在代码上并打开属性对话框时,它会显示if (SessionManager.groupSettings.Count > 0)对象不为null。生成的调用堆栈在这里,但表示源代码行是[NullReferenceException: Object reference not set to an instance of an object.] Project.Default.Page_Load(Object sender, EventArgs e) in C:\Users\ASP\Project\Project\Default.aspx.cs:20 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51 System.Web.UI.Control.OnLoad(EventArgs e) +95 System.Web.UI.Control.LoadRecursive() +59 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2952 ,它位于代码隐藏中:

public static sessionStart()

我的第二次尝试包含上面静态构造函数中的所有代码,但是它是在if方法中使用的,该方法在调用页面的代码隐藏中的第一个protected void Page_Load(object sender, EventArgs e) { SessionManager.sessionStart() if (SessionManager.groupSettings.Count > 0) { pnlDashboard.Visible = true; pnlLogin.Visible = false; getDisplayData(); } else { pnlDashboard.Visible = false; pnlLogin.Visible = true; } } 语句之上调用:< / p>

Any

我真的很难过可能导致这个问题的原因。我的代码中的其他地方有静态类,没有任何问题,Session似乎不是null。

我感谢所有人的帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

所以我似乎没有在我的SessionStore类中初始化一些对象,因为我添加了一个初始化它们的构造函数,现在问题已得到修复。当对象被序列化时,问题是实际上正在发生(就像将对象存储到状态服务器中一样),并且错误消息使我感到困惑。

编辑 - 我总是这样做...在我发布到StackOverflow之后找出解决方案...... :(