if (Session["UserID"] == null || Session["UserID"].ToString() == "")
Response.Redirect("Login.aspx");
重複、易寫錯、若 Session 物件本身為 null 會拋出例外(極少見但理論上可能)。
// 定義於共用工具類別
public static Func
if (string.IsNullOrEmpty(IsLogin(Session["UserID"])))
Response.Redirect("Login.aspx?msg=登入逾時");
public class UserInfo { public int UserId; public string Name; public string Role; }
public static Func
UserInfo user = GetUser(Session["CurrentUser"]);
if (user.UserId == -1) Response.Redirect("Login.aspx");
// 直接使用強型別物件
lblWelcome.Text = "歡迎," + user.Name;
string.IsNullOrEmpty(Session["UserID"] as string)?若 Session 中**完全不存在該 Key**,Session["UserID"] 回傳 null,as string 結果為 null,`IsNullOrEmpty` 可正常處理。**但若 Session 物件本身為 null**(極罕見,如 Session 模式切換瞬間),直接存取會拋出 NullReferenceException。Func 封裝可集中防禦。
public abstract class SecurePage : Page
{
protected UserInfo CurrentUser { get; private set; }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CurrentUser = Session["CurrentUser"] as UserInfo;
if (CurrentUser == null) Response.Redirect("~/Login.aspx?ReturnUrl=" + Server.UrlEncode(Request.RawUrl));
}
}
業務頁面繼承 SecurePage 即自動擁有 CurrentUser 強型別屬性,編譯期檢查、IntelliSense 完整支援。