登錄成功 → 實體存入 Session → 勾選「記住我」則將 UserId 寫入 Cookie(有效期 3 天) → 後續訪問:Session 為空時讀取 Cookie → 查詢用戶實體 → 回寫 Session → 實現免登錄。
BlogUserBLL bll = new BlogUserBLL();
// 1. 驗證用戶名密碼(密碼已 MD5)
List<BlogUser> list = bll.GetModelList("LoginName='" + name + "' and LoginPwd='" + md5Pwd + "'");
if (list.Count > 0) {
// 2. 存入 Session
Context.Session["uInfo"] = list[0];
// 3. 記住登錄 → 寫 Cookie
if (!string.IsNullOrWhiteSpace(remember)) {
HttpCookie cookie = new HttpCookie("uid", list[0].Id.ToString());
cookie.Expires = DateTime.Now.AddDays(3);
Context.Response.Cookies.Add(cookie);
}
Response.Write("<script>alert('登錄成功');window.location='BlogList.aspx'</script>");
} else {
Response.Write("<script>alert('登錄失敗');window.location='/Login.aspx'</script>");
}
Response.End();
所有需登錄頁面繼承 BasePage,重寫 OnInit 實現統一攔截:
protected override void OnInit(EventArgs e) {
if (Session["uInfo"] == null) {
// 嘗試從 Cookie 恢復
if (Request.Cookies["uid"] != null) {
BlogUserBLL bll = new BlogUserBLL();
BlogUser umodel = bll.GetModel(int.Parse(Request.Cookies["uid"].Value));
Session["uInfo"] = umodel;
return;
}
// 完全未登錄 → 跳轉登錄頁
Response.Redirect("/Login.aspx");
}
base.OnInit(e);
}
關鍵點:OnInit 是頁面生命周期早期事件,在此攔截可避免後續邏輯執行;BasePage 僅適用 .aspx 頁面,.ashx 需單獨實現 BaseHandler。