更改ASP.NET的会话状态cookie的到期日期
我正在使用ASP.NET会话状态来跟踪我的网站上登录的用户。
但是,我遇到的一个问题是,默认情况下,ASP.NET会话cookie在浏览器关闭时设置为过期。
http://ahb.me/43e
我尝试使用类似于以下代码的东西设置我自己的ASP.NET_SessionId cookie并修改cookie的到期时间:
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(1);
这些方法都不起作用,它们都设置了第二个具有相同名称的cookie。
有没有办法改变会话cookie的到期日期?
我建议您使用FormsAuthentication来跟踪登录用户。 您可以使用持久性FormsAuthenticationCookie来实现您想要的function。
或者,如果您确实想使用会话状态,请尝试使用此技术 。
基于Joe的答案中的链接,我想出了这种方法:
public void Application_PostRequestHandlerExecute(object sender, EventArgs e) { UpdateSessionCookieExpiration(); } /// /// Updates session cookie's expiry date to be the expiry date of the session. /// /// /// By default, the ASP.NET session cookie doesn't have an expiry date, /// which means that the cookie gets cleared after the browser is closed (unless the /// browser is set up to something like "Remember where you left off" setting). /// By setting the expiry date, we can keep the session cookie even after /// the browser is closed. /// private void UpdateSessionCookieExpiration() { var httpContext = HttpContext.Current; var sessionState = httpContext?.Session; if (sessionState == null) return; var sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection; var sessionCookie = httpContext.Response.Cookies[sessionStateSection?.CookieName ?? "ASP.NET_SessionId"]; if (sessionCookie == null) return; sessionCookie.Expires = DateTime.Now.AddMinutes(sessionState.Timeout); sessionCookie.HttpOnly = true; sessionCookie.Value = sessionState.SessionID; }
此代码可以插入Global.asax.cs
。
只是一个猜测:也许编辑web.config中的session.configuration可能会改变cookie过期? 你可以看看这里 ?
我认为试图长时间保持会话是错误的方法,并限制了你的可扩展性。 会话cookie指向由服务器上的IIS维护的特定会话。 通常,您希望在用户关闭浏览器后关闭会话,以便不占用非活动用户的所有可用服务器资源。 您希望离开的用户的会话关闭,并且资源可供新到达的用户使用。 这就是会话cookie到期的原因。
如果您想在用户关闭浏览器后维护某些用户状态,您可以随时查看“ 个人资料”等内容 。 或者,如果这是购物车之类的东西,您可以将购物车保存在数据库中,然后在再次登录时将其重新连接到用户。
Tom的回答几乎对我有用,除了将cookie转换为变量并设置其属性。 我必须直接设置对象的属性,如下所示:
HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = expiryDate; HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].HttpOnly = true; HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value = sessionState.SessionID;
我仍然将cookie转换为变量以检查它是否为null,如果是,则返回。