我試圖實現一個靜態SessionManager
類,該類應該充當圍繞SessionStore
對象的包裝,該對象存儲在HttpContext.Current.Session["objSession"]
中,並實際上保存了用戶的所有會話數據。 SessionManager
類具有與SessionStore
相同的屬性,但具有根據需要操作會話數據所需的額外方法。基本上,SessionManager
便於獲取/設置會話對象中存儲的屬性。C#ASP.NET會話管理器引發空引用異常
所有類都存儲在與Web解決方案相同的名稱空間中,並且都是可序列化的。
我已經嘗試了兩種不同的解決方案,我的問題,無論是在相同的點拋出一個空引用異常,試圖做任何HttpContext.Current.Session
時:調用頁的
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)
,這是在後臺代碼:
[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;
}
}
我真的很爲難,什麼可能會造成這個問題。我的代碼中的其他地方有靜態類,並沒有任何問題,並且會話似乎不爲空。
我感謝所有幫助。謝謝!
'SessionManager.groupSettings'那是什麼 – spender
一個'名單'實際上似乎是我的問題的原因...我初始化'SessionStore'內的所有屬性,似乎問題是固定的(也許它不能序列化空對象?)。我沒有再遇到錯誤,會議似乎保持了所有的價值,我的下一個問題是調試器現在將「逐步過渡」視爲「繼續」。 –
ToxicPineapple