views:

19

answers:

1

If I create a cookie (in ASP.NET) like this

cookie = new HttpCookie("MyCookie");
cookie["foo"] = "bar";
Response.Cookies.Add(cookie);

will the value be empty/null if the session expires?

My goal is to persist the data in the cookie only while the browser remains open even if the user is not actively interacting with the application.

+2  A: 

No, it won't be cleared with session, it'll expire when you set it to, or when the browser closes :)

By default a cookie without a set expiration is transmitted to the client that way (no expiration info). Again by default this means the browser should hang onto the cookie but not persist it to disk, so it's not 1:1 with the session expiring, but rather whenever you close the browser.

Examples:

  • If I visit your site, go idle for an hour, even though my session has expired I will still send the cookie on the next request. If I closed the browser (all tabs, depending on browser) and tried again, I wouldn't be sending the cookie.
  • If I visited your site, got the cookie, closed my browser, opened another (before session timeout) I would still have the same session but not that cookie.

Perhaps you would be better off storing this data in Session?


A session expires by a cookie (the session cookie) having no meaning on the server anymore. When the session expires, even if the cookie's on the client, the server gets the cookie and goes "well...can't find a session for that".

That being said, you can continually push the cookie, having the same expiration as the session (20 min from request, by default). Or, you could include the session ID in the cookie, and when the server gets the cookie, disregard the cookie's value if the session ID doesn't match.

Nick Craver
Even if I do not set an expiration time or make it persistent?
Andy Evans
@Andy - Kind of...by default the cookie isn't stored to disk when an expiration isn't provided, so it's not 1:1 with loss of session, but when they *close the browser* it's gone. If that's good enough, you're all set. I'll update the answer to make this point a bit clearer.
Nick Craver
Thanks. I was getting confused with the session cookie.
Andy Evans