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

ano*_*ard 6 c# asp.net cookies session 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);
Run Code Online (Sandbox Code Playgroud)

这些方法都不起作用,它们都设置了具有相同名称的第二个cookie.

有没有办法改变会话cookie的到期日期?

Tom*_*rek 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;
}
Run Code Online (Sandbox Code Playgroud)

可以插入此代码Global.asax.cs.


Joe*_*Joe 2

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

或者,如果您确实想使用会话状态,请尝试此技术