以下方法有缺陷,请参见我的另一篇文章《利用Cache、Timer(ATLAS)控制用户重复登陆的可行性方法》
网上看到可用Cache来判断用户是否已登陆的方法,感觉还不错。实验后,特此分享代码
原理比较简单:
判断cache中是否已存在规定的客户登陆字符串,如果没有便添加,同时指定其在cache中的保存时间。重复登陆时,便能通过判断cache值是否为空来判断用户是否重复登陆了。
//生成Key
string sKey = TextBox1.Text + "_IsLogin";
//得到Cache中的给定Key的值
string sUser = Convert.ToString(Cache[sKey]);

//检查是否存在
if (sUser == null || sUser == String.Empty)

{
//Cache中没有该Key的项目,表明用户没有登录,或者已经登录超时
//TimeSpan 表示一个时间间隔,获取系统对session超时作的设置值
//TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
//(如果考虑到允许用户再次登陆的时间小于session超时时间,可将此值设小,在此示例中设置为一分钟)
TimeSpan SessTimeOut = new TimeSpan(0, 0, 1, 0, 0);
HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut,
System.Web.Caching.CacheItemPriority.NotRemovable, null);
//首次登录,您可以做您想做的工作了。
Label1.Text = "你好!欢迎光临";
}
else

{
//在Cache中发现该用户的记录,表名已经登录过,禁止再次登录
Label1.Text = "对不起,你已在别处登陆.或者在1分钟后重试";
return;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步