一个简单的防止同一ID重复登陆的方法

     主要思路是一个账号登陆就在缓存中注册一个ID,如果这个账号对应ID在缓存中存在,这不允许重复登陆。考虑到非正常退出等其他非正常问题。引用asp.net的ajax的timer控件结合session过期机制来插入和删除缓存ID

    第一步,用户登陆的时候,判断缓存ID是否存在,如果存在表示已经登陆,不允许再次登陆,如果不存在这登陆成功,并开始注册一个缓存ID。代码如下:

Code
string sKey = username.Text.Trim() + "_Login";
string sUser = Convert.ToString(Cache[sKey]);
if (sUser == null || sUser == string.Empty)
{
TimeSpan SessTimeOut
= new TimeSpan(0, 0, 0, 5, 0);
HttpContext.Current.Cache.Insert(sKey, sKey,
null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
[
"reload"] = false;
}
else
{
Response.Write(
"<script>alert('您的用户身份已经登陆!!!') </script>");
Session[
"reload"] = true;
return;
}

其中设置缓存ID存在的时候为5秒。超过5秒就失效。用户还在线,失效后怎么办,看第二步。

   第二步,进入Default页,首先判断Session["reload"]是否为true,如果值为true,则timer控件开始运行,this.Timer1.Enabled=true; timer能运行后,所写代码如下:

Code
protected void Timer1_Tick(object sender, EventArgs e)
{
try
{
if (Session["yonghuid"] != null)
{
//生成key
string sKey = Session["yonghuid"] + "_Login";
string sUser = Convert.ToString(Cache[sKey]);
TimeSpan SessTimeOut
= new TimeSpan(0, 0, 0, 5, 0);
if (sUser != null)
{
HttpContext.Current.Cache.Remove(sKey);
}
HttpContext.Current.Cache.Insert(sKey, sKey,
null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
}
else
{
this.Timer1.Enabled = false;
}
}
catch
{

}
}

其中,由于timer控件不停的异步刷新,如果非正常与服务器断开连接,则会弹出scriptmanager的错误提示,我们可以在前台的script中加入以下js

Code
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args)
{
if (args.get_error() != undefined)
{
args.set_errorHandled(
true);
}
}
</script>

   这些都是我的个人见解,如果有什么错误请更正,不甚感激。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值