需求:同一用戶同一時間僅允許一處登入。常見做法是用 Application 變數記錄已登入用戶 ID,登入時檢查,登出時移除。但瀏覽器直接關閉不會觸發 Session_End,導致殘留記錄。本文提供兩種補救方案。
// 登入時檢查
string userId = txtUser.Text;
ArrayList list = Application["GLOBAL_USER_LIST"] as ArrayList ?? new ArrayList();
if (list.Contains(userId)) { /* 提示已登入 */ return; }
list.Add(userId);
Application["GLOBAL_USER_LIST"] = list;
// Session_End 移除
void Session_End(object sender, EventArgs e)
{
string userId = Session["SESSION_USER"] as string;
ArrayList list = Application["GLOBAL_USER_LIST"] as ArrayList;
if (userId != null && list != null)
{
list.Remove(userId);
Application["GLOBAL_USER_LIST"] = list;
}
}
注意:Session_End 僅在 sessionState mode="InProc" 時觸發。
function window.onbeforeunload() {
if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
window.open("logout.aspx");
}
}
logout.aspx 執行與 Session_End 相同的移除邏輯,並自動關閉視窗。Session_End 觸發清理。此法不依賴客戶端腳本,相容性最好,是工業級常用做法。