.net 环境下 防止多用户登陆

来源:互联网 发布:广东省 人工智能 政策 编辑:程序博客网 时间:2024/06/07 18:46
protected void Login1_Authenticate(object sender,AuthenticateEventArgs e)
 
   {
       //验证 处理
       if (Membership.ValidateUser(Login1.UserName,Login1.Password))
       {
           UserOnLine online = new UserOnLine();
           //生成Key  
           string sKey = Login1.UserName + "_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);
               //首次登录,您可以做您想做的工作了。
               DataView dv = online.GetData(Login1.UserName);
               if (dv.Count > 0)
               {
                   Login1.FailureText = "用户已登陆";
                   e.Authenticated = false;
               }
               else
               {
                   online.UserName = Login1.UserName;
                   online.Add();
                   Session["UserKey"] = Login1.UserName;
                   e.Authenticated = true;
               }
           }
           else
           {
               Login1.FailureText = "用户已登陆";
               e.Authenticated = false;
           }
       }
    }
原创粉丝点击