技术贴: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源码下载 

另外推广下自己的没落的维持生计的小店,园友可以享受优惠

你可能感兴趣的:(asp.net)