asp.net 防止用户重复多次登录实例代码详解

有的时候,我们做的系统中要防止用户重复登录这个时候我们可以 使用 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 等。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值