首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 應用程式層級驗證登入:HttpModule 與 Generic Handler 實作

     編輯:ASP.NET 基礎

透過實作 `IHttpHandler` + `IReadOnlySessionState` 的 Generic Handler (`.ashx`),在 `web.config` 註冊 ``,攔截特定路徑下所有 `.aspx` 請求,集中驗證 `Session["UID"]`,未登入導向登入頁。同樣原理適用防盜連、防下載。

1. 建立 Handler 類別庫專案

  • 專案名:`IHandlers` (Class Library)
  • 加入 `ASHX`:`HandleSession.ashx` (實際為 `.cs` 檔)
  • 參考 `System.Web`、`System.Web.SessionState`

2. Handler 完整程式碼

using System.Web;
using System.Web.SessionState;

namespace IHandlers {
    public class HandleSession : IHttpHandler, IReadOnlySessionState {
        public bool IsReusable => true;

        public void ProcessRequest(HttpContext context) {
            // 僅允許讀取 Session,不修改,故用 IReadOnlySessionState
            if (context.Session["UID"] == null) {
                context.Response.Redirect("~/Login.aspx?ReturnUrl=" + 
                    HttpUtility.UrlEncode(context.Request.RawUrl));
            }
        }
    }
}

3. 編譯並部署

  1. Build `IHandlers.dll`
  2. 主網站專案 `References` → `Add Reference` → 選 `IHandlers.dll`

4. web.config 註冊 (IIS 6/7 經典模式)

<configuration>
  <system.web>
    <httpHandlers>
      <add verb="*" path="temp/*.aspx" type="IHandlers.HandleSession, IHandlers" />
    </httpHandlers>
  </system.web>
  
  <!-- IIS 7+ 整合模式需同時註冊在 system.webServer -->
  <system.webServer>
    <handlers>
      <add name="SessionCheck" verb="*" path="temp/*.aspx" 
           type="IHandlers.HandleSession, IHandlers" preCondition="integratedMode" />
    </handlers>
  </system.webServer>
</configuration>
  • `path="temp/*.aspx"`:僅攔截 `/temp/` 目錄下 `.aspx`,可改 `path="*.aspx"` 全站攔截。
  • `type="命名空間.類別名, 組件名"`

5. 進階:改用 HttpModule (更符合架構)

public class AuthModule : IHttpModule {
    public void Init(HttpApplication app) {
        app.AuthorizeRequest += (s, e) => {
            var ctx = HttpContext.Current;
            if (ctx.Session["UID"] == null && 
                !ctx.Request.Path.EndsWith("Login.aspx", StringComparison.OrdinalIgnoreCase)) {
                ctx.Response.Redirect("~/Login.aspx?ReturnUrl=" + 
                    HttpUtility.UrlEncode(ctx.Request.RawUrl));
            }
        };
    }
    public void Dispose() { }
}

`web.config` 註冊:`` (system.web/httpModules 或 system.webServer/modules)。

優勢:模組在管線早期 (`AuthorizeRequest`) 執行,效能優於 Handler;可集中處理所有靜態/動態資源驗證。

應用延伸

  • 防盜連:檢查 `Request.UrlReferrer.Host` 是否為本域。
  • 防下載:驗證 `Session["DownloadToken"]` 或簽名 URL。
  • API 限流:在 `BeginRequest` 統計 IP 頻率。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved