技术贴: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(); } } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步