利用Cache防止同一帐号重复登录 (c#)

来源:互联网 发布:丹麦安徒生博物馆知乎 编辑:程序博客网 时间:2024/05/18 02:06

我们只要把每次用户登录后的用户信息存储在Cache中,把Cache的Key名设为用户的登录名,Cache的过期时间设置为Session的超时时间,在用户每次登录的时候去判断一下Cache[用户名]是否有值,如果没有值,证明该用户没有登录,否则该用户已登录。

具体实现请看下例:

   protected void btnLogin_Click(object sender, EventArgs e)
        {
            string strUser = string.Empty;
            string strCacheKey = txtName.Text;
            string pass = txtPass.Text;
            string mac = GetMac();
            strUser = Convert.ToString(Cache[strCacheKey]);
            if (strUser == string.Empty)
            {
                TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);

              Cache.Insert(strCacheKey, strCacheKey, null, DateTime.MaxValue, SessTimeOut, CacheItemPriority.NotRemovable, null);

 

                Tbl_Users user = new Tbl_Users();
                user = Tbl_UsersManage.GetUserByNameAndPass(strCacheKey, pass, out user);
               if (user != null && user.vchUserMAC == mac)    
                {
                    Session["User"] = strCacheKey;
                    Response.Redirect("UserTest.aspx");
                }
                else
                {
                    MessageBox.Show("用户不存在,请重新登录!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                }
                this.Label1.Text = Session["User"].ToString();
            }
            else
           {
              this.Label1.Text = "这个用户已经登录!";
           }
        }

原创粉丝点击