开发者

cookie isn't updated until page refresh... how to avoid that?

开发者 https://www.devze.com 2023-02-11 01:30 出处:网络
I have some asp.net pages that read and write cookie values.During the life cycle of a page it may update the cookie value and then need to read it again further in the code.What I\'ve found is that i

I have some asp.net pages that read and write cookie values. During the life cycle of a page it may update the cookie value and then need to read it again further in the code. What I've found is that it's not getting the latest value of the cookie until a page refresh. Is there a way around this? Here's the code I'm using to set and get the values.

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] = sessio开发者_运维技巧nValue;
            cookie.Expires = DateTime.Now.AddHours(1);
            HttpContext.Current.Response.Cookies.Set(cookie);
        }


What you're missing is that when you update the cookie with SetValue you're writing to the Response.Cookies collection.

When you call GetValue you're reading from the Request.Cookies collection.

You need to store the transient information in a way that you access the current information, not just directly the request cookie.

One potential way to do this would be to writer a wrapper class that with rough psuedo code would be similar to

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 = ? }); 
        }    
}

I ran into needing to do similar code just this week. The cookie handling model is very strange.


Start using Sessions to store your information, even if it's only temporary.

Cookies rely on a header being sent to the browser before the page has rendered. If you've already sent information to the client then proceed to set a cookie, you're going to see this "page refresh delay" you've described.

If it's necessary to have this value, use a session variable between the time you set the cookie and when you refresh the page. But, even then I would just recommend avoiding settings cookies so late in the processing step and try to set it as early as possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消