建立一個Class SessionManager,裡面包含著目前登入的Session清單
static class SessionManager { public static List SessionList = new List(); }
在登入時紀錄登入者帳號到Session,並且加入到Session清單
Session["Mail"] = user.Email;//記錄使用者帳號 SessionManager.SessionList.Add(Session);
這邊在登入就可以記錄每個使用者的Session去做操作,接下來做檢查重複登入的帳號並且把它移除
var s = SessionManager.SessionList.Where(x => x["Mail"] != null && user.Email.Equals(x["Mail"])); List<string> deleteList = new List<string>(); if (s != null && s.Count() >= 1) { foreach (var ss in s) { deleteList.Add(ss.SessionID);//增加到預刪除清單 ss.Abandon();//中斷使用者Session ss.Clear();//清空所有key value } //進行Session剔除 SessionManager.SessionList.RemoveAll(x => deleteList.Contains(x.SessionID)); }
完整的登入程式碼如下
Session["Mail"] = user.Email; var s = SessionManager.SessionList.Where(x => x["Mail"] != null && user.Email.Equals(x["Mail"])); List<string> deleteList = new List<string>(); if (s != null && s.Count() >= 1) { foreach (var ss in s) { deleteList.Add(ss.SessionID); ss.Abandon(); ss.Clear(); } SessionManager.SessionList.RemoveAll(x => deleteList.Contains(x.SessionID)); } SessionManager.SessionList.Add(Session);
記得在登出的部分也要加上相關機制來處理SessionList