在 ASP.NET WebForms 中,登錄後將用戶信息存入 Session,並在其他頁面讀取時,若直接調用 Session["UNAME"].ToString() 容易拋出「對象引用未設置為對象的實例」異常。這是因為 Session 可能為 null(如會話過期、應用程序池回收、跨域訪問等)。
// 登錄頁存儲
Session["UID"] = UID;
Session["UNAME"] = UserName;
// 其他頁面讀取
var User = Session["UNAME"].ToString(); // 若 Session["UNAME"] 為 null,此處拋出異常
推薦使用擴展方法或輔助類進行防空判斷:
public static string GetSessionString(this HttpSessionState session, string key)
{
return session[key]?.ToString() ?? string.Empty;
}
// 使用
var userName = Session.GetSessionString("UNAME");
if (!string.IsNullOrEmpty(userName))
{
// 業務邏輯
}
建立靜態類 CurrentUser 統一管理:
public static class CurrentUser
{
public static string UserName
{
get => HttpContext.Current.Session["UNAME"]?.ToString();
set => HttpContext.Current.Session["UNAME"] = value;
}
public static bool IsLoggedIn => !string.IsNullOrEmpty(UserName);
}
// 登錄時
CurrentUser.UserName = UserName;
// 業務代碼中
if (CurrentUser.IsLoggedIn)
{
var name = CurrentUser.UserName;
}
.ToString()。HttpContext.Current.Session 為 null。採用防空取值模式並封裝用戶上下文,能從根本上避免 NullReferenceException,提高代碼健壯性與可維護性。