[英]Why does the session return null?
我無法寫入會話變量。
這是我的源代碼:
public class CurrentUser
{
public static string UserName
{
get
{
if (HttpContext.Current.Session["UserName"] != null)
return (string)HttpContext.Current.Session["UserName"];
else
return null;
}
set
{
HttpContext.Current.Session["UserName"] = value;
}
}
}
我稱這門課為寫作:
public class SQLGetData
{
public UserDC LogIn()
{
UserDC userDC = new UserDC();
CurrentUser.Id = 1;
CurrentUser.UserName = "Admin";
userDC.id = 1;
userDC.UserName = "Admin";
return userDC;
}
}
當我想打電話給(MasterPage.aspx)時:
Label1.Text = CurrentUser.Id + CurrentUser.UserName;
結果: CurrentUser.Id為1且CurrentUser.UserName為NULL 。
為什么CurrentUser.UserName為NULL? 如何修改此公共字符串UserName進行寫入?
從您共享的代碼中,無法真正幫助您,因為我們只能嘗試猜測正在發生的事情。
我假設您的CurrentUser類具有一個Id屬性,其代碼與用戶名類似。 Id屬性可以正常工作,但不能使用用戶名...聽起來確實很奇怪。
您可以共享課程的完整代碼嗎? 或至少是Id屬性的代碼?
然后,這也將有助於了解從何處調用SQLGetData類。 身份驗證如何工作?
我對此類會話為null的情況的看法是-在應用程序中存在隱藏的錯誤,但沒有發現。 代碼中的任何異常都將終止會話,並可能會繼續執行新的會話,因此這些值將為null ...
最好的方法是,在所有異常處理程序上使用debug-> exceptions菜單在vside中運行您的開發環境代碼,並針對幾種情況在應用程序中運行,最終您將意識到存在隱藏的錯誤,這些錯誤源自諸如convertToInt之類的簡單錯誤或類似的參考錯誤。 ,這會導致會話變為null ...但是我猜事情並沒有在“錯誤”頁面的錯誤處中斷,而是通過“調試”上方的所有異常ON選項找到了。
希望能幫助到你! 海德科技
您應該首先使用以下方法將“ UserName”引入到會話中
HttpContext.Current.Session.Add("UserName", value)
在你的二傳手中。
public class CurrentUser
{
public static string UserName
{
get
{
if (HttpContext.Current.Session["UserName"] != null)
return (string)HttpContext.Current.Session["UserName"];
else
return null;
}
set
{
if (HttpContext.Current.Session["UserName"] == null)
HttpContext.Current.Session.Add("UserName", value);
else
HttpContext.Current.Session["UserName"] = value;
}
}
}
完成后,它應該可以像您寫的那樣工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.