if (Session["UserID"] == "" || Session["UserID"] == null)
Response.Redirect("../Login.aspx?m=逾時");
Session["key"] 不會拋例外但回傳 null,後續 .ToString() 才會 NullReference。public static class AuthHelper
{
// 回傳 string,若無效則回傳 String.Empty
public static Func<object, string> IsLogin = session => session as string ?? string.Empty;
// 回傳 User 物件,若無效則回傳預設 User (Id = -1)
public static Func<object, User> IsLoginUser = session => session as User ?? new User { UserID = -1 };
}
if (string.IsNullOrEmpty(AuthHelper.IsLogin(Session["UserID"])))
Response.Redirect("../Login.aspx?m=逾時");
User currentUser = AuthHelper.IsLoginUser(Session["CurrentUser"]);
if (currentUser.UserID == -1)
Response.Redirect("../Login.aspx");
// 後續直接使用 currentUser.Name 等屬性
as 安全轉型 + ?? 提供預設值,避免例外。在全域攔截器中統一驗證,失敗直接導向登入頁,Controller/Page 完全不用寫驗證碼。