asp.net下一个账号不允许多个用户同时在线,重复登陆的代码,需要的朋友可以参考下。
方法一: 复制代码 代码如下: string sKey = username.Text.ToString().Trim(); // 得到Cache中的给定Key的值 string sUser = Convert.ToString(Cache[sKey]); // 检查是否存在 if (sUser == null || sUser == String.Empty) { TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);//取得Session的过期时间 HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);//将值放入cache己方便单点登录 //成功登录 } else if (Cache[sKey].ToString() == sKey)//如果这个账号已经登录 { ClientScript.RegisterStartupScript(GetType(), "提示", "<script>alert('对不起,当前用户已经登录');</script>"); return; } else { Session.Abandon();//这段主要是为了避免不必要的错误导致不能登录 } 复制代码 代码如下: //关闭浏览器或窗口时清空Cache的方法.在主页面aspx文件中加入一个onunload事件.通过ajax清空hOnline中的Session.SessionID window.onunload=function(){ $.ajax({ type: "POST", data:"sKey="+sKey; url: "online.aspx" }); } online.aspx.cs代码 复制代码 代码如下: protected void Page_Load(object sender, EventArgs e) { HttpContext.Current.Cache.Remove(sKey); } //在Global.asax文件中的Session_End方法里加入 //Session过期后.清空hOnline中的Session.SessionID Hashtable hOnline = (Hashtable)Application["Online"]; if (hOnline[Session.SessionID] != null) { hOnline.Remove(Session.SessionID); Application.Lock(); Application["Online"] = hOnline; Application.UnLock(); } 方法二: 复制代码 代码如下: //sKey为登录用户名 if(ApplicationOnline(username.Text.tirm())){ Hashtable hOnline = new Hashtable(); hOnline[Session.SessionID] = sKey; Application.Lock(); Application["Online"] = hOnline; Application.UnLock(); }
public Boolean ApplicationOnline(string sKey) { Boolean flag = true; Hashtable hOnline = (Hashtable)Application["Online"]; if (hOnline != null) { IDictionaryEnumerator idE = hOnline.GetEnumerator(); while (idE.MoveNext()) { //if (idE.Key != null && idE.Key.ToString().Equals(Session.SessionID)) //{ if (idE.Value != null && sKey.Equals(idE.Value.ToString())) { flag = false; } break; //} } } return flag; }
//关闭浏览器或窗口时清空Session.SessionID的方法.在主页面aspx文件中加入一个onunload事件.通过ajax清空Session.SessionID window.onunload=function(){ $.ajax({ type: "POST", url: "online.aspx" }); } online.aspx.cs代码 复制代码 代码如下: protected void Page_Load(object sender, EventArgs e) { Hashtable hOnline = (Hashtable)Application["Online"]; if (hOnline[Session.SessionID] != null) { hOnline.Remove(Session.SessionID); Application.Lock(); Application["Online"] = hOnline; Application.UnLock(); } }
|