ASP.NET 原生 HttpContext.Current.Session 雖然方便,但直接在業務代碼中散落字串鍵值、型別轉換、空值判斷,極易導致拼寫錯誤、NullReferenceException 以及維護困難。建立一個靜態輔助類 CSession,集中管理鍵名常數、提供強型別存取、內建預設值與例外處理,能大幅提升代碼健壯性與可讀性。
public static class CSession
{
/// 取得物件,不存在回傳 null
public static object Get(string key) => HttpContext.Current.Session[key];
/// 取得字串,不存在回傳 String.Empty
public static string GetString(string key)
{
object obj = HttpContext.Current.Session[key];
return obj?.ToString() ?? string.Empty;
}
/// 取得物件,不存在回傳指定預設值
public static object Get(string key, object defaultValue)
=> HttpContext.Current.Session[key] ?? defaultValue;
/// 取得物件,不存在且允許新增時自動寫入預設值
public static object Get(string key, object defaultValue, bool canAdd)
{
if (HttpContext.Current.Session[key] == null)
{
if (canAdd) HttpContext.Current.Session.Add(key, defaultValue);
return defaultValue;
}
return HttpContext.Current.Session[key];
}
}
同一個方法根據值是否為 null 與鍵是否存在,自動決定 Add、索引器賦值或 Remove,並包裝 try-catch 回傳布林結果。
public static bool Set(string key, object value)
{
try
{
var session = HttpContext.Current.Session;
if (value == null && session[key] != null)
{
session.Remove(key); // 值為 null 且鍵存在 → 刪除
}
else if (session[key] == null)
{
session.Add(key, value); // 鍵不存在 → 新增
}
else
{
session[key] = value; // 鍵存在 → 更新
}
return true;
}
catch (Exception ex)
{
// CMsgBox.Show(ex.Message); // 視專案日誌框架而定
return false;
}
}
| 需求 | 方法 | 說明 |
|---|---|---|
| 清除全部 Session | Session.Abandon() | 立即終結當前 Session,觸發 Session_End 事件,下一請求將建立新 SessionID。 |
| 移除單一鍵值 | Session["Key"] = null; | 將值設為 null,鍵仍保留在集合中(Count 不變)。 |
| 徹底移除單一鍵 | Session.Remove("Key"); | 從集合中移除鍵值對,Count 遞減。 |
SessionKeys 靜態類,集中定義所有鍵名字串,避免魔術字串散落。Get<T>(this HttpSessionState, string),進一步簡化型別轉換。[Serializable]。