gpt4 book ai didi

asp.net - cookie 在页面刷新之前不会更新......如何避免这种情况?

转载 作者:行者123 更新时间:2023-12-01 11:57:57 25 4
gpt4 key购买 nike

我有一些可以读取和写入 cookie 值的 asp.net 页面。在页面的生命周期中,它可能会更新 cookie 值,然后需要在代码中进一步读取它。我发现它在页面刷新之前不会获得 cookie 的最新值。有没有解决的办法?这是我用来设置和获取值的代码。

public static string GetValue(SessionKey sessionKey)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiePrefix];
if (cookie == null)
return string.Empty;

return cookie[sessionKey.SessionKeyName] ?? string.Empty;
}

public static void SetValue(SessionKey sessionKey, string sessionValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiePrefix];
if (cookie == null)
cookie = new HttpCookie(cookiePrefix);

cookie.Values[sessionKey.SessionKeyName] = sessionValue;
cookie.Expires = DateTime.Now.AddHours(1);
HttpContext.Current.Response.Cookies.Set(cookie);
}

最佳答案

您缺少的是,当您使用 SetValue 更新 cookie 时,您正在写入 Response.Cookies 集合。

当您调用 GetValue 时,您正在从 Request.Cookies 集合中读取数据。

您需要以访问当前信息的方式存储 transient 信息,而不仅仅是直接访问请求 cookie。

一种可能的方法是编写一个包装类,其粗略的伪代码类似于

public CookieContainer(HttpContext context)
{
_bobValue = context.Request.Cookies["bob"];
}

public Value
{
get { return _bobValue; }
set {
_bobValue = value;
_context.Response.Cookies.Add(new Cookie("bob", value) { Expires = ? });
}
}

就在本周,我遇到了需要执行类似代码的情况。 cookie 处理模型非常奇怪。

关于asp.net - cookie 在页面刷新之前不会更新......如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5017732/

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