实现单点登陆,实现方式为,比如,同一个用户已经登陆,而又在别处再次登陆,不会阻止这次登陆,而是在第一次登陆的界面刷新时,提示被迫下线,这个原理跟MSN类似,保证每个用户名只可有一个登陆在线
首先,在登陆页的事件中写下面的代码:
protected void Login_Click(object sender, EventArgs e)
{
Hashtable hOnline = (Hashtable)Application["Online"];
if (hOnline != null)
{
IDictionaryEnumerator idE = hOnline.GetEnumerator();
string strKey = "";
while (idE.MoveNext())
{
if (idE.Value != null && idE.Value.ToString().Equals(UserName.Text))
{
strKey = idE.Key.ToString();
hOnline[strKey] = "XXXXXX";
break;
}
}
}
else
{
hOnline = new Hashtable();
}
hOnline[Session.SessionID] = UserName.Text;
Application.Lock();
Application["Online"] = hOnline;
Application.UnLock();
}
再建一个BasePage.cs类,继承自Page,重写OnInit,如下代码:
protected override 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))
{
if (idE.Value != null && "XXXXXX".Equals(idE.Value.ToString()))
{
hOnline.Remove(Session.SessionID);
Application.Lock();
Application["Online"] = hOnline;
Application.UnLock();
ShowAndUrlMessageBox("被迫下线.", "Login.aspx");
}
}
break;
}
}
}
另外,在Global.asax中,
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
Hashtable hOnline = (Hashtable)Application["Online"];
if (hOnline[Session.SessionID] != null)
{
hOnline.Remove(Session.SessionID);
Application.Lock();
Application["Online"] = hOnline;
Application.UnLock();
}
}