更改ASP.NET的会话状态cookie的到期日期

时间:2010-06-09 08:40:02

标签: c# asp.net session cookies session-state

我正在使用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的到期日期?

5 个答案:

答案 0 :(得分:6)

基于Joe的回答中的链接,我想出了这种方法:

public void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
    UpdateSessionCookieExpiration();
}

/// <summary>
/// Updates session cookie's expiry date to be the expiry date of the session.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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

答案 1 :(得分:2)

我建议您使用FormsAuthentication来跟踪登录用户。您可以使用持久性FormsAuthenticationCookie来实现您想要的目标。

或者,如果您确实想使用会话状态,请尝试this technique

答案 2 :(得分:1)

只是猜测:也许编辑web.config中的session.configuration可能会改变cookie过期?你可以看看here

答案 3 :(得分:1)

我认为尝试长时间保持会话是错误的方法并限制了您的可扩展性。会话cookie指向由服务器上的IIS维护的特定会话。通常,您在用户关闭浏览器后关闭 想要 会话,以便不会占用非活动用户的所有可用服务器资源。您希望离开的用户的会话关闭,并且资源可供新到达的用户使用。这就是会话cookie到期的原因。

如果您想在用户关闭浏览器后维护某些用户状态,您可以随时查看Profile之类的内容。或者,如果这是购物车之类的东西,您可以将购物车保存在数据库中,然后在用户再次登录时将其重新连接到用户。

答案 4 :(得分:1)

除了将cookie转换为变量并设置其属性之外,Tom的回答几乎对我有用。我必须直接设置对象的属性:

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,如果是,则返回。