透過實作 `IHttpHandler` + `IReadOnlySessionState` 的 Generic Handler (`.ashx`),在 `web.config` 註冊 `
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));
}
}
}
}
<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>
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` 註冊:`
優勢:模組在管線早期 (`AuthorizeRequest`) 執行,效能優於 Handler;可集中處理所有靜態/動態資源驗證。