【问题标题】:cookie isn't updated until page refresh... how to avoid that?cookie 在页面刷新之前不会更新......如何避免这种情况?
【发布时间】:2016-06-10 22:51:25
【问题描述】:

我有一些读取和写入 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);
        }

【问题讨论】:

    标签: asp.net cookies


    【解决方案1】:

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

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

    您需要以访问当前信息的方式存储临时信息,而不仅仅是直接访问请求 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处理模型很奇怪。

    【讨论】:

      【解决方案2】:

      开始使用 Sessions 来存储您的信息,即使它只是临时的。

      Cookie 依赖于在页面呈现之前发送到浏览器的标头。如果您已经向客户端发送了信息,然后继续设置 cookie,您将看到您所描述的“页面刷新延迟”。

      如果需要此值,请在设置 cookie 和刷新页面之间使用会话变量。但是,即便如此,我还是建议避免在处理步骤中太晚设置 cookie,并尽可能早地设置它。

      【讨论】:

      • 这就是我们要解决的全部问题。我们在一个拥有 400 多个站点的网络农场中。每个站点的 id 从服务器到服务器都不相同,因此基于数据库的会话不起作用,当然,在网络场中,inproc 会话不起作用。所以我们不能使用会话。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2021-01-04
      相关资源
      最近更新 更多