首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET WebForms 使用 Session 驗證登入狀態,防止未授權直接訪問管理頁面

     編輯:程式設計綜合問答

核心邏輯

  1. 登入頁 驗證成功後:Session["User"] = userInfo;
  2. 受保護頁面 Page_Load 檢查:
protected void Page_Load(object sender, EventArgs e) {
    if (Session["User"] == null) {
        Response.Redirect("login.aspx?returnUrl=" + Server.UrlEncode(Request.RawUrl));
    }
}

完整範例

login.aspx.cs

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 = "帳號或密碼錯誤";
    }
}

default.aspx.cs (管理頁)

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();
}

進階建議

  • BasePage 類別:建立繼承 Page 的 BasePage,在 OnInit 統一驗證,所有管理頁繼承 BasePage 即可。
  • Web.config 全域授權:
    <location path="admin">
      <system.web>
        <authorization>
          <deny users="?" /> <!-- 拒絕匿名 -->
        </authorization>
      </system.web>
    </location>
    需配合 Forms Authentication 模組。
  • Session 超時處理:web.config 設定 <sessionState timeout="20" />,超時自動導向登入頁。

總結

Session + 頁面驗證(或 Web.config 授權)是 ASP.NET WebForms 最基礎的權限控制模式,簡單有效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved