您的位置:首页 > 编程语言 > ASP

asp.net 中关于防止用户重复登录的问题

2009-06-06 17:34 597 查看
有的时候,我们做的系统中要防止用户重复登录这个时候我们可以 使用 Context.Cache 和hashtable 来执行这样的操作。

1.在global.asax 中的 Application_Start()写上

void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
Hashtable h=new Hashtable();
Context.Cache.Insert("online",h);

}

2.在登陆页面

login.aspx.cs

protected void login1_Click(object sender, ImageClickEventArgs e)
{

if ((name.Value != "") && (psw.Value != ""))//输入项是否为空
{
Hashtable h = (Hashtable)Context.Cache.Get("online");

if (h != null)//判断hashtable 是否为空
{
//判断哈希表中是否有该用户
IDictionaryEnumerator e1 = h.GetEnumerator();
bool flag = false;
while (e1.MoveNext())// 循环遍历查找该用户
{
if (e1.Value.ToString() == name.Value.ToString())
{ // 找到 该用户
flag = true;
break;
}
}
if (flag) //已经登陆
{

psw.Value = "";
name.Value = "";
Response.Write("<script language='javascript'>alert('登陆失败!原因:您的账号已经登录或浏览器异常关闭!');location.href='login.aspx';</script>");
return;
}
else
{
//哈希表不为空 且 此用户未登录
if (判断数据库表中是否存在该用户)
{//存在 就执行下面的语句

h.Add(Session.SessionID, Session["userid"]);
//h[Session.SessionID] = Session["userid"].ToString();
Context.Cache.Insert("online", h);

write_user_log();// 往数据库里写信息
}
}
}
else
{
//哈希表为空
if (判断数据库表中是否存在该用户)
{
h.Add(Session.SessionID, Session["userid"]);
Context.Cache.Insert("online", h);

write_user_log();// 往数据库里写信息
}
}
}
}

3.在退出页面

protected void Page_Load(object sender, EventArgs e)
{
LogoutCache();// 这里需要注意,logoutCache()必须在清空session 之前执行,要不 将会出错
updateTimeIntegral();//执行 数据库相关操作,最后清空session 可以使用Session.Abandon();
Response.Write("<script language='javascript'>alert('您已经退出本站');window.opener=null;window.open('','_self');window.close();</script>");
}
public void LogoutCache() // 退出 删除该用户在hashtable 中的信息
{
Hashtable h = (Hashtable)Context.Cache["online"];
if (h != null)
{
if (h[Session.SessionID] != null)
{
h.Remove(Session.SessionID);
Context.Cache.Insert("online", h);
}
}
}

有人会说可以使用global 的session_end()和 Application_end()

但是如果客户端没有是在点击X退出去的呢,这个时候是不会触发 global 中的这两个事件的。所以,不能依靠

这两个事件即时清空session 等。

这个只是在客户端正常退出的情况下的使用。另外 在非正常情况下的退出 以后会给出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: