How to make an ASP.NET session cookie expire with the ASP.NET HttpSession?
Asked Answered
K

1

4

I have created an HttpCookie in order to share data across a subdomain :

HttpCookie cookie = new HttpCookie("sessionGUID");
cookie.Value = value;
cookie.Domain = ".example.com";

Response.Cookies.Set(cookie);

I carelessly assumed since it is a 'session' cookie (no expires) that it would expire along with my ASP.NET session. Of course to the browser this is a 'browser session' cookie and not linked to the ASP.NET session.

What I want to do is expire these 'browser session' cookies along with the ASP.NET session.

i think I just need to set Expires to the same value as the ASP.NET session. How would i determine this programatically?

Koopman answered 7/12, 2008 at 4:28 Comment(0)
Y
1

If they just need to be close then something like this:

int expirationMinutes = Session.Timeout;
if (System.Web.HttpContext.Current.Response.Cookies["monster"]!=null)
{
    System.Web.HttpContext.Current.Response.Cookies["monster"].Expires =
                                 DateTime.Now.AddMinutes(expirationMinutes);
}

The session timer resets everything the user posts or gets, so since code is executing on the server right now, the remaining time on the current session is Session.Timeout, say 20 minutes.

In 20 minutes, the cookie will not be accepted and you'll have to issue a new one.

Yoheaveho answered 7/12, 2008 at 4:55 Comment(3)
doh. i did look on the Session object, but i was too lazy to scroll down and see the Timeout property. it didnt look like it had anything interesting on it at first glance, and I couldnt find it on some of the other objects. thanks!Koopman
The Session object has its timeout reset on each page request. So unless this code will be executed on each request, the cookie expiration will quickly get out of sync with the Session expiration.Colene
The Expires property is an absolute DateTime, while Session.Timeout is an int duration in minutes. These don't relate; this doesn't compile.Thrombo

© 2022 - 2024 — McMap. All rights reserved.