且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 cookie 设置为在会话结束时过期?网站

更新时间:2023-11-30 22:46:10

您说的是非持久性 cookie.默认情况下,asp.net 以这种方式发送 cookie.它们之间的主要区别在于持久性 cookie 设置了 expires 值.

You're talking about a non-persistent cookie. By default asp.net sends cookies in that way. The main difference between them are that a persistent cookie has an expires value set.

因此,如果您不希望 cookie 持久化,则不要设置 expires 值.

So, if you don't want the cookie to persist, then do not set the expires value.

也就是说,cookie 将保留在内存中,直到浏览器实际关闭.假设他们浏览到您的网站并且您设置了一个非持久性 cookie.他们做事并浏览.稍后,他们使用相同的浏览器实例返回您的站点.cookie 仍然存在.

That said, the cookie will remain in memory until the browser is actually closed. Let's say they browse to your site and you set a non-persistent cookie. They do things and browse away. Later they, using the same browser instance, come back to your site. The cookie will still be there.

现在,如果他们在任何时候关闭浏览器,那么 cookie 将被清除.

Now, if they closed the browser at any point, then the cookie would be flushed out.

重点是,不要设置 expires 标头.尤其是在会话日期到期时.会话日期通常只有 20 分钟左右,但到期日期会随着用户浏览您的网站而向前滚动.

Point is, don't set the expires header. Especially not to when the session date expires. Session dates are generally only 20 or so minutes in the future, but the expiration date rolls forward as the user browses through your site.

====== 更新 ======

===== update =====

我使用以下代码进行测试:

I used the following code for testing:

    protected void Page_Load(object sender, EventArgs e) {
        if (!Page.IsPostBack) {
            HttpCookie c = Request.Cookies["test"];
            if (c != null) {
                Response.Write(String.Format("test value is {0} <br />", c.Value));
            }
        } else {
            HttpCookie c = new HttpCookie("test");
            c.Value = "HERE IT IS";
            Response.Cookies.Add(c);
        }
    }

    protected void Button1_Click(object sender, EventArgs e) {
        Response.Write("clicked<br />");
    }

.aspx 文件简单有一个按钮,它触发了 button1_click 处理程序.当我最初使用任何最新的浏览器(即 firefox、chrome)浏览它时,没有 cookie.单击按钮后,设置了一个 cookie.然后我完全关闭浏览器,重新打开并浏览回该站点.在所有情况下,cookie 都不见了.

the .aspx file simple had a button which fired that button1_click handler. When I initially browse to it using any of the latest browsers (ie, firefox, chrome) there is no cookie. After I click the button a cookie is set. Then I closed the browser completely, reopened and browsed back to the site. In all cases the cookie was gone.