| Asp.net防止论坛用户重复登录的方法 |
| 本例完成的功能就是防止用户重复登录!若用户已经 登录,则当其再次登录时,弹出提示框后返回! 实现思路:用户登录成功后,将用户登录信息存放到 Hashtable类型的Application["Online"]里面,其键 值为SessionID,其Value值为用户ID;当用户注销时 ,调用Session.Abandon;在Global.asax里面的 SessionEnd事件中,将用户ID从Hashtable中删除;在 用户访问页面时,察看Hashtable中是否有对应的用户 ID如果没有则判断用户不在线(用户不在线的原因可 能是按了注销按钮、网页超时等) 1、公用类中判断用户是否在线的函数(供用户调用) /// <summary> /// 判断用户strUserID是否包含在Hashtable h中 /// </summary> /// <param name="strUserID"></param> /// <param name="h"></param> /// <returns></returns> public static bool AmIOnline(string strUserID,Hashtable h) { if(strUserID == null) return false; //继续判断是否该用户已经登陆 if(h == null) return false; //判断哈希表中是否有该用户 IDictionaryEnumerator e1 = h.GetEnumerator(); bool flag = false; while(e1.MoveNext()) { if(e1.Value.ToString().CompareTo(strUserID) == 0) { flag = true; break; } } return flag; } 2、用户登录事件处理: private void btnlogin_Click(object sender, System.Web.UI.ImageClickEventArgs e) { ////User为自定义的类,其中包含Login方法 User CurUser = new User(); CurUser.UserID = this.username.Text.Trim(); if(MyUtility.AmIOnline(CurUser.UserID, (Hashtable)Application["Online"])) { JScript.Alert("您所使用的登录ID已经在线了!您不 能重复登录!"); return; } CurUser.LoginPsw = FormsAuthentication.HashPasswordForStoringInCon figFile(this.password.Text.Trim(),"SHA1"); int ii = CurUser.Login(); StringBuilder sbPmt = new StringBuilder(); switch(ii) { case 0: //如果登录成功,则将UserID加入 Application["Online"]中 Hashtable h = (Hashtable)Application["Online"]; if(h == null) h = new Hashtable(); h[Session.SessionID] = CurUser.UserID; Application["Online"] = h; Session["UserID"] = CurUser.UserID; Session["UserNM"] = CurUser.UserNM; Session["RoleMap"] = CurUser.RoleMap; Session["LoginPsw"] = CurUser.LoginPsw; Session["LoginTime"] = DateTime.Now; Response.Redirect("ChooseRole.aspx"); break; case -1: JScript.Alert("用户名错误!"); break; case -2: JScript.Alert("密码错误!"); break; default: sbPmt.Append("登录过程中发生未知错误!"); JScript.Alert(sbPmt.ToString()); break; } return; } 3、在Global.asax中的Session_End事件: protected void Session_End(Object sender, EventArgs e) { Hashtable h=(Hashtable)Application["Online"]; if(h[Session.SessionID]!=null) h.Remove(Session.SessionID); Application["Online"]=h; } 4、在每一个页面需要刷新的地方,调用如下代码: try { if(!common.MyUtility.AmIOnline(Session ["UserID"].ToString(),(Hashtable)Application ["OnLine"])) { //用户没有在线 ,转到登录界面 Response.Write ("<script>parent.document.location.href='Login. aspx';</script>"); ////有框架时用 //Response.Redirect("login.aspx"); ////无框架时 用 return; } } catch { //会话过期 ,转到登录界面 Response.Write ("<script>parent.document.location.href='Login. aspx';</script>"); ////有框架时所用 //Response.Redirect("login.aspx"); ////无框架时 用 return; } 深入思考: 由本例的解决方法可以加以延伸,比如,在存储 UserID的时候,将UserID+客户端IP地址一起存进去, 则在将相应信息取出来分析的时候,可以做到:当用 户在不同的计算机上先后登录的时候,则允许最近一 次的登录,而将之前的登录删除!等等等等 |
浙公网安备 33010602011771号