您的位置:首页 > 编程语言

cache和session配合实现单点登录的关键代码以及对session存在时间过长的处理

2016-12-12 16:35 393 查看


//实现思路   

//利用Cache的功能,把用户的登录信息保存在Cache中,并设置过期时间为Session失效的时间,因此,一旦Session失效,Cache也过期;而Cache对所有的用户都可以访问,因此,用它保存用户信息比数据库来得方便。   

//代码如下 :  

    protected void Button1_Click(object sender, EventArgs e)

    {

        string userName = this.txtUserName.Text;

        string password = txtPassWord.Text;

       

        if (Page.IsValid == true)

        {

            if (IsLogin(userName, password))

              //  Response.Redirect("css/error.aspx?" + "&ErrorMessage=" + "用户已经登录,请重新输入!");

                Response.Write("<h2 style='color:red'>用户已经登录,请重新输入!");

            else   

                if (userName == "1" && password == "1")

                {

                    Response.Write("<h2 style='color:red'>你好,登录成功!");

                }

        } 

      

    }

 private bool IsLogin(string UserCode, string UserName)

    {

        string ExistsUser = Convert.ToString(Cache[UserCode]);

        if (ExistsUser == null || ExistsUser == String.Empty)

        {

            TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);

            HttpContext.Current.Cache.Insert(UserCode, UserName, null, DateTime.MaxValue, SessTimeOut,

                                             System.Web.Caching.CacheItemPriority.NotRemovable, null);

            Session["User"] = UserCode;

            return false;

        }

        else

        {

            return true;

        }

    } 

}

但是有一个问题就是session存在的时间很长,如果用户不主动注销,那么直接关闭浏览器以后,就会导致用户无法登录。

看了学长博客,得到了启发,我们可以采取这样一个方法,如果用户没有主动的注销,让它打开网页变保持登录就好。

在page_load事件里面添加如下代码

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

string str_User = Convert.ToString(Cache[Convert.ToString(Session["User"])]);

// Cache中没有该str_Key的项目,表名用户没有登录,或者已经登录超时

if (str_User != String.Empty)

{

Response.Write("<h2 style='color:red'>你好,登录成功!");

}

}

//以下是清理Cache

//System.Web.Caching.Cache _cache = HttpRuntime.Cache;

            //_cache.Remove("1");

            _cache.Remove(key);

 

         

 

         

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐