Session 逾時控制使用者閒置多久後自動登出或清除伺服器端快取資料。設定得當可平衡安全性與使用者體驗。ASP.NET 提供兩種標準設定方式:程式碼動態指定與組態檔宣告。
// 設定為 1 分鐘(單位:分鐘)
Session.Timeout = 1;
適用位置:
Global.asax → Session_Start:全站統一預設值。BasePage.OnInit:依角色/權限差異化設定。注意事項:
StateServer 或 SQLServer 模式,逾時值仍由應用程式端控制,但需確保機器金鑰一致。
<configuration>
<system.web>
<!-- mode: InProc | StateServer | SQLServer | Custom -->
<sessionState mode="InProc" timeout="20" />
</system.web>
</configuration>
屬性說明:
| 屬性 | 說明 |
|---|---|
mode | 儲存模式:InProc (預設, 進程內)、StateServer (獨立服務)、SQLServer (資料庫)、Custom (自訂提供者) |
timeout | 逾時分鐘數 (預設 20),整數 1~525600 (1 年) |
cookieless | UseUri / UseDeviceProfile / AutoDetect / False (預設) |
stateConnectionString | StateServer 模式時指定 TCP 連線字串 (如 tcpip=127.0.0.1:42424) |
sqlConnectionString | SQLServer 模式時指定資料庫連線字串 |
Web.config 為應用程式層級預設值,應用程式啟動時讀取。Session.Timeout = x 為目前 Session 實例覆寫,優先序高於組態檔。Web.config 數值。Session.Timeout 立即生效,無需重啟應用程式。
protected void Session_Start(object sender, EventArgs e) {
// 預設值
Session.Timeout = 20;
}
public void Login(string username, bool rememberMe) {
// 驗證通過後
var user = GetUser(username);
Session["User"] = user;
Session.Timeout = rememberMe ? 60 : 20; // 管理員可再拉長
if (user.IsAdmin) Session.Timeout = 120;
}
<forms timeout="30" /> 是**表單驗證票據**逾時,非 Session 逾時,兩者獨立運作。Session.Abandon() 會立即結束 Session,但 Session_End 事件僅在 InProc 模式觸發。StateServer/SQLServer 模式下,逾時清理由背景工作排程執行,非即時,允許數分鐘誤差。StateServer 或 SQLServer,並同步 machineKey。
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load() {
Response.Write("Web.config timeout: " +
System.Web.Configuration.WebConfigurationManager
.GetSection("system.web/sessionState")
.Cast<System.Web.Configuration.SessionStateSection>()
.First().Timeout.TotalMinutes);
Response.Write("<br/>Current Session.Timeout: " + Session.Timeout);
}
</script>