Session["User"] = userInfo;Page_Load 檢查:protected void Page_Load(object sender, EventArgs e) {
if (Session["User"] == null) {
Response.Redirect("login.aspx?returnUrl=" + Server.UrlEncode(Request.RawUrl));
}
}
protected void btnLogin_Click(object sender, EventArgs e) {
if (ValidateUser(txtUser.Text, txtPwd.Text)) {
Session["User"] = txtUser.Text; // 或存 User 物件
string returnUrl = Request.QueryString["returnUrl"];
Response.Redirect(string.IsNullOrEmpty(returnUrl) ? "default.aspx" : returnUrl);
} else {
lblMsg.Text = "帳號或密碼錯誤";
}
}
protected void Page_Load(object sender, EventArgs e) {
if (Session["User"] == null) {
Response.Redirect("login.aspx?returnUrl=" + Server.UrlEncode(Request.RawUrl));
}
lblWelcome.Text = "歡迎, " + Session["User"].ToString();
}
Page 的 BasePage,在 OnInit 統一驗證,所有管理頁繼承 BasePage 即可。<location path="admin">
<system.web>
<authorization>
<deny users="?" /> <!-- 拒絕匿名 -->
</authorization>
</system.web>
</location>
需配合 Forms Authentication 模組。web.config 設定 <sessionState timeout="20" />,超時自動導向登入頁。Session + 頁面驗證(或 Web.config 授權)是 ASP.NET WebForms 最基礎的權限控制模式,簡單有效。