如何指定 cookie 过期日期?

How to assign cookie expiry date?

我正在尝试了解 cookie。但是有一点我不能理解。希望你能帮我。

我写了一个简短的代码:

using System;
using System.Web;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["Test2"] == null)
            {
                Response.Cookies["Test2"]["Address"] = "Home";
                Response.Cookies["Test2"].Expires = DateTime.Now.AddSeconds(60);
            }

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Cookies["Test2"]["Address"] = "Work";
        }
    }
}

首先,我想检查是否有一个名为 "Test2" 的 cookie。它创建一个名为 "Test2" 的 cookie。它的到期日期是创建后一分钟。

然后,我单击按钮,它传递 if 子句并将地址更改为工作。但是,当我查看 cookie 过期日期时,它已经消失了。

Expires: When the browsing session ends

为什么这个有效期会改变?请你帮助我好吗?

您正在尝试修改 cookie ,这将 创建一个新的 cookie ,并且由于您没有指定 ExpiryDate 它将仅限于会话将结束。

ASP.NET Cookies Overview

You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

另外:

If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded.

因此您的选择是要么不修改 cookie 值(使用其他机制,如 DB),要么在每次修改时指定不同的到期日期。