以淘寶購物流程為例,探討 ASP.NET 中如何利用 Session 管理用戶登入狀態,並比較兩種常見的驗證架構模式。
每個受保護頁面在 Page_Load 中檢查 Session 標記。
public partial class Login : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { }
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {
Session["UserFlag"] = false; // 預設未登入
if (ValidateUser(Login1.UserName, Login1.Password)) {
Session["UserFlag"] = true;
e.Authenticated = true;
Response.Redirect("Main.aspx");
} else {
Response.Write("帳號或密碼錯誤");
}
}
private bool ValidateUser(string userName, string password) {
using (var conn = new SqlConnection("server=.;database=User;uid=sa;pwd=123456;")) {
conn.Open();
// 實務上請使用參數化查詢防 SQL 注入
using (var cmd = new SqlCommand(
"SELECT COUNT(*) FROM UserInfo WHERE UserName=@u AND Password=@p", conn)) {
cmd.Parameters.AddWithValue("@u", userName);
cmd.Parameters.AddWithValue("@p", password); // 實務應存雜湊值
return (int)cmd.ExecuteScalar() > 0;
}
}
}
}
public partial class Main : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
// 防止直接輸入 URL 繞過登入
if (Session["UserFlag"] == null || !(bool)Session["UserFlag"]) {
Response.Redirect("Login.aspx");
}
}
}
建立中介頁面 Judge.aspx,所有受保護頁面跳轉前先導向此頁驗證,通過才轉回目標頁。優點:驗證邏輯集中維護;缺點:多一次導向、URL 參數傳遞目標頁較繁瑣。
public partial class Judge : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
string returnUrl = Request.QueryString["ReturnUrl"] ?? "Default.aspx";
if (Session["UserFlag"] == null || !(bool)Session["UserFlag"]) {
Response.Redirect("Login.aspx?ReturnUrl=" + Server.UrlEncode(returnUrl));
} else {
Response.Redirect(returnUrl);
}
}
}
受保護頁面改為:
// Main.aspx
protected void Page_Load(object sender, EventArgs e) {
if (Session["UserFlag"] == null || !(bool)Session["UserFlag"]) {
Response.Redirect("Judge.aspx?ReturnUrl=" + Server.UrlEncode(Request.RawUrl));
}
}
手寫 Session 驗證僅適合教學或極簡專案。正式專案強烈建議使用 ASP.NET 內建 Forms Authentication:
Web.config 設定 <authentication mode="Forms">。FormsAuthentication.SetAuthCookie(username, false) 發票票據。[Authorize] 屬性或 User.Identity.IsAuthenticated 判斷。cookieHttpOnly="true"、requireSSL="true"、regenerateExpiredSessionId="true"。Session 是 HTTP 無狀態協議下維持用戶狀態的基石。從「每頁檢查」到「中央攔截」,再到框架級的 Forms Authentication,架構演進的核心是將驗證邏輯從業務代碼中分離,實現關注點分離與安全性保障。