1)
密码验证后:
- Hashtable hOnline = (Hashtable)Application["Online"];
- if (hOnline != null)
- {
- int i = 0;
- while (i<hOnline.Count) //因小BUG所以增加此判断,强制查询到底
- {
- IDictionaryEnumerator idE = hOnline.GetEnumerator();
- string strKey = "";
- while (idE.MoveNext())
- {
- if (idE.Value != null && idE.Value.ToString().Equals(this.username.Text))
- {
- //already login
- strKey = idE.Key.ToString();
- hOnline[strKey] = "XXXXXX";
- break;
- }
- }
- i = i + 1;
- }
- }
- else
- {
- hOnline = new Hashtable();
- }
- hOnline[Session.SessionID] = this.username.Text;
- Application.Lock();
- Application["Online"] = hOnline;
- Application.UnLock();
- //用户登录的时候将登录用户名放在一个全局变量Online,Online为Hashtable结构,
- //Key为SessionID,Value为用户名。每次用户登录时均判断以下要登录的用户名在Online中是不是已经存在,
- //如果存在该用户名已经被登录,将第一个人登录的SessionID对应的用户名强制变更为XXXXXX,表示该登录将被强制注销
2)
建立一个CommonPage页,系统中所有的页面都继承于CommonPage页(
public partial class index : CommonPage
),在CommonPage页的后台代码中添加如下代码:
- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Collections;
- /// <summary>
- /// CommonPage 防止用户多点登录
- /// </summary>
- public class CommonPage: System.Web.UI.Page
- {
- public CommonPage()
- {
- //
- // TODO: 在此处添加构造函数逻辑
- //
- }
- override protected void OnInit(EventArgs e)
- {
- 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))
- {
- //already login
- if (idE.Value != null && "XXXXXX".Equals(idE.Value.ToString()))
- {
- hOnline.Remove(Session.SessionID);
- Application.Lock();
- Application["Online"] = hOnline;
- Application.UnLock();
- string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
- Response.Write(string.Format(js, "帐号已在别处登录 ,你将被强迫下线(请保管好自己的用户密码)!", "logout.aspx?cname=noadmin"));
- return;
- }
- break;
- }
- }
- }
- }
- }
继承于CommonPage的页面在刷新时都要执行重载的OnInit中的代码,取出Online,找到该用户对应的SessionID,判断SessionID里对应的用户名是否变更,如果变更,就强迫下线,清掉Session,转到Login画面。
3) 最后需要在Session过期或者退出系统时释放资源,在Global.asax文件中的Session_End中添加如下代码:
3)
- Hashtable hOnline = (Hashtable)Application["Online"];
- if(hOnline[Session.SessionID] != null)
- {
- hOnline.Remove(Session.SessionID);
- Application.Lock();
- Application["Online"] = hOnline;
- Application.UnLock();
- }