开发者

Are cookies created in ASP.NET bound by session timeouts?

开发者 https://www.devze.com 2023-01-08 19:43 出处:网络
If I create a cookie (in ASP.NET) like this cookie = new HttpCookie(\"MyCookie\"); cookie[\"foo\"] = \"bar\";

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

cookie = new HttpCookie("MyCookie");
cookie["foo"] = "bar";
Response.Co开发者_StackOverflowokies.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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消