1

Here is the scenario. A cookie with the key "MyCookie" has been set on a previous request. I can access it via HttpContext.Request.Cookies.Get("MyCookie"). I want to perform an update such as adding another value to the Cookie Values collection, but I'm not 100% sure I am doing it right.

Am I doing this correctly in the following example?

   public static void UpdateCookie(HttpContext context, string cookieName, Action<HttpCookie> updateCookie){
        var cookie = context.Request.Cookies.Get(cookieName);
        updateCookie(cookie);
        context.Response.Cookies.Set(cookie);
   }
smartcaveman
  • 38,142
  • 26
  • 119
  • 203
  • 1
    Is this question better suited to http://codereview.stackexchange.com/? I'm not sure. – Randy supports Monica Apr 01 '11 at 19:10
  • 1
    @Tuzo, I don't think so. My question is just about how to do something correctly. The code snippet is not something from my application. It's just the best way that I could think of to explain my current understanding. If you look at the first paragraph of the FAQ on http://codereview.stackexchange.com/faq, you will see it explicitly says Code Review is for questions that are **"not about... best practices"** – smartcaveman Apr 01 '11 at 19:19

1 Answers1

1

To update a cookie, you need only to set the cookie again using the new values. Note that you must include all of the data you want to retain, as the new cookie will replace the previously set cookie. I'm going to assume that your implementation of updateCookie() does just that.

Otherwise, your general premise is correct. Here's an implementation I've used many times to do just that. (Note: _page is a reference to the current Page):

/// <summary> 
/// Update the cookie, with expiration time a given amount of time from now.
/// </summary>
public void UpdateCookie(List<KeyValuePair<string, string>> cookieItems, TimeSpan? cookieLife)
{
    HttpCookie cookie = _page.Request.Cookies[COOKIE_NAME] ?? new HttpCookie(COOKIE_NAME);

    foreach (KeyValuePair<string, string> cookieItem in cookieItems)
    {
        cookie.Values[cookieItem.Key] = cookieItem.Value;
    }

    if (cookieLife.HasValue)
    {
        cookie.Expires = DateTime.Now.Add(cookieLife.Value);
    } 
    _page.Response.Cookies.Set(cookie);
}
Donnelle
  • 5,508
  • 3
  • 23
  • 31
John M. Wright
  • 4,291
  • 43
  • 61
  • 1
    Setting response cookie based on requests cookie can cause writing some cookie properties that we don't want like SameSite=None. Example default SameSite value is set to -1 or to Lax this value is not send back by browser to server and request cookie have SameSite=None which is not what we want when we sent it again to browser. (I'm just fixing similar piece of code in my application, related to recent Chrome changes) – CoperNick Jul 07 '20 at 21:56