技術貼:asp.net實現唯一賬戶在線 禁止同一帳號同時在線 asp.net實現您的帳號在別處登錄,您已被迫下線!


技術要點:

Application 全局變量的使用

hashtable 的使用

Session 對應唯一sessionID 標志會話狀態

webpage 繼承 BasePage的技術 

整體比較簡單,主要是思想

 

private void SetOnlineInfo(HttpContext context, string username)
        {
            Hashtable hOnline = (Hashtable)context.Application["Online"];//讀取全局變量
            if (hOnline != null)
            {
                IDictionaryEnumerator idE = hOnline.GetEnumerator();
                string strKey = "";
                while (idE.MoveNext())
                {
                    if (idE.Value != null && idE.Value.ToString().Equals(username))//如果當前用戶已經登錄,
                    {
                        //already login            
                        strKey = idE.Key.ToString();
                        hOnline[strKey] = "XX";//將當前用戶已經在全局變量中的值設置為XX
                        break;
                    }
                }
            }
            else
            {
                hOnline = new Hashtable();
            }

            hOnline[context.Session.SessionID] = username;//初始化當前用戶的
            context.Application.Lock();
            context.Application["Online"] = hOnline;
            context.Application.UnLock();
        }
protected void CheckOtherLogin(HttpContext context)
        {

            Hashtable hOnline = (Hashtable)Application["Online"];//獲取已經存儲的application值
            if (hOnline != null)
            {
                IDictionaryEnumerator idE = hOnline.GetEnumerator();
                while (idE.MoveNext())
                {
                    if (idE.Key != null && idE.Key.ToString().Equals(context.Session.SessionID))
                    {
                        //already login
                        if (idE.Value != null && "XX".Equals(idE.Value.ToString()))//說明在別處登錄
                        {
                            hOnline.Remove(Session.SessionID);
                            context.Application.Lock();
                            context.Application["Online"] = hOnline;
                            context.Application.UnLock();
                            context.Response.Write("<script>alert('你的帳號已在別處登陸,你被強迫下線!');window.location.href='login.aspx';</script>");//退出當前到登錄頁面
                            context.Response.End();
                        }
                    }
                }
            }
        }

 demo源碼下載 

另外推廣下自己的沒落的維持生計的小店,園友可以享受優惠


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM