.Net Session 关闭浏览器后需要重新登录

按照道理来说,启用了Session之后,服务器会一直存储会话通信。但是在实际的体验过程中,我发现浏览器一关闭,重新打开页面就需要重新登录了。

原因是这样的:

服务器怎么判断客户端是这个用户对应的Session呢? 因为http协议是无状态的请求协议,根本就不知道是谁发起的这个请求。在.net测试环境中,cookie会在登录完成的时候,自动增加一个 ASP.NET_SessionId的值。

那么问题来了,这个ASP.NET_SessionId是什么呢?

原来在会话中,服务器把SessionID放在客户端浏览器的内存Cookie中,所以每次关闭的时候,都会清除浏览器的内存,导致需要重新登录了。

那解决这个就很简单了。我们只需要把内存Cookie中的值放入物理Cookie中就可以了。

首先在登录完成的时候,往客户端写入Cookie

1     HttpCookie cookie = new HttpCookie("ASP.NET_SessionId");
2                 cookie.Value = HttpContext.Current.Session.SessionID;
3                 cookie.Expires = DateTime.Now.AddDays(1);
4                 HttpContext.Current.Response.Cookies.Add(cookie);

OK,接下来在登录验证的时候,增加Cookie判断,如果存在值,则直接返回Ture。这个时候服务器会自动获取到这个SessionID对应的用户。

     if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value != "")
                {
                    //HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value = HttpContext.Current.Request.Cookies["JSESSIONID"].Value;
                    return true;
                }
            }

 上面的代码容易导致Session已经过期,但是本地存储的Session还没到期,应该再加一层判断。当Cookie中的SessionID在服务器存在的时候,则直接登录,不存在则重新登录

 if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value != "")
                {
                    //HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value = HttpContext.Current.Request.Cookies["JSESSIONID"].Value;
                    if (HttpContext.Current.Session["Account"] != null)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                    return false;
            }
            else
                return false;

 

posted @ 2019-09-29 09:49  Alex_Mercer  阅读(586)  评论(0)    收藏  举报