gpt4 book ai didi

asp.net - 为什么 ASP.NET 中的 cookie 过期日期无法跨 session 保存?

转载 作者:行者123 更新时间:2023-12-02 18:34:15 35 4
gpt4 key购买 nike

我对测试平台页面进行了一些更改,因此我可以在这里使我的问题更清楚。

该页面有三个按钮:设置;清除;并获取。

Set 有以下代码:

PreferredCookie = new HttpCookie("PreferredCookie");
PreferredCookie.Value = "Chocolate Chip";
DateTime exp = DateTime.Now.AddDays(1.0d);
PreferredCookie.Expires = exp;
Response.Cookies.Set(PreferredCookie);

清晰有这个:

HttpCookie PreferredCookie = Request.Cookies["PreferredCookie"];
if (PreferredCookie != null)
{
PreferredCookie.Value = "";
PreferredCookie.Expires = DateTime.Now;
Response.Cookies.Set(PreferredCookie);
}

Get 有这个,它输出到 asp:Literal:

HttpCookie PreferredCookie = Request.Cookies["PreferredCookie"];
if (PreferredCookie != null)
{
CookieLiteral.Text = "Value = " + PreferredCookie.Value + "<br>";
CookieLiteral.Text += "Expires = " + PreferredCookie.Expires.ToString("MM/dd/yyyy HH:mm:ss");
}
else
{
CookieLiteral.Text = "<h2>No Cookie?</h2>";
}

如果我启动页面并单击“清除”,然后单击“获取”,我会看到:

No Cookie?

如果我单击“设置”,然后单击“获取”,我会看到:

Value = Chocolate Chip
Expires = 01/01/0001 00:00:00

此日期似乎被视为永不过期。如果我使用 Firefox 访问该页面,会得到相同的结果。

最佳答案

简短回答 -您无法读取 cookie 的到期日期和时间。

答案稍长 - 这不是 ASP.NET 中的 session 问题。这是一个关于您可以从 ASP.NET 中的 cookie 服务器端读取什么内容的问题。 Per the MSDN :

The browser is responsible for managing cookies, and the cookie's expiration time and date help the browser manage its store of cookies. Therefore, although you can read the name and value of a cookie, you cannot read the cookie's expiration date and time. When the browser sends cookie information to the server, the browser does not include the expiration information. (The cookie's Expires property always returns a date-time value of zero.)

You can read the Expires property of a cookie that you have set in the HttpResponse object, before the cookie has been sent to the browser. However, you cannot get the expiration back in the HttpRequest object.

所以基本上,cookie 过期日期设置正确。这可以通过检查浏览器中的 cookie 来验证。不幸的是,像在 Get 函数中那样读取此 cookie 将返回 1/1/0001。

如果您确实想要获取过期时间,那么您必须将其存储在 cookie 本身中:

设置

DateTime exp = DateTime.Now.AddDays(1);
HttpCookie PreferredCookie = new HttpCookie("PreferredCookie");
PreferredCookie.Values.Add("cookieType", "Zref");
PreferredCookie.Values.Add("exp", exp.ToString());
PreferredCookie.Expires = exp;
Response.Cookies.Set(PreferredCookie);

获取

HttpCookie PreferredCookie = Request.Cookies["PreferredCookie"];
if (PreferredCookie != null)
{
CookieLiteral.Text = "Value = " + PreferredCookie["cookieType"] + "<br>";
CookieLiteral.Text += "Expires = " + PreferredCookie["exp"];
}
else
{
CookieLiteral.Text = "No Cookie";
}

关于asp.net - 为什么 ASP.NET 中的 cookie 过期日期无法跨 session 保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21441125/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com