Changing expiry on ASP.NET's Session State cookie

anonymous coward picture anonymous coward · Jun 9, 2010 · Viewed 8.5k times · Source

I'm using ASP.NET Session State to keep track of logged in users on my site.

However, one problem I'm running into is that by default ASP.NET session cookies are set to expire when the browser closes.

http://ahb.me/43e

I've tried setting my own ASP.NET_SessionId cookie and modifying the cookie's expiry using something similar to the following code:

Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(1);

None of these approaches work, they all set a second cookie with the same name.

Is there a way of changing the session cookie's expiry?

Answer

Tom Pažourek picture Tom Pažourek · Sep 13, 2016

Based on links in Joe's answer, I figured out this approach:

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;
}

This code can be inserted in Global.asax.cs.