title: MVC Cookie losing values after a HTTP Request & Cookie Add value
body: <p>I have a multi key-value pair cookie. The cookie is a session cookie, i.e. not persistent. It contains several key-value pairs of data and well within the 4k size limit.</p>
  
  <p><strong>What's working:</strong> In my initialise action method (on Controller A), the cookie has a number of key-value pairs successfully added to it. All good so far.</p>
  
  <p><strong>Problem:</strong> When I navigate to another page, i.e. different action method (on Controller B), and then add a value to the cookie, I find all the previous values in the Cookie are now gone.</p>
  
  <p>Please note, I verified the problem occurs only when a new value is added here. NOT adding a value to the cookie and navigating across many pages (and controllers) the existing values in the cookie are all preserved.</p>
  
  <p><strong>Investigations:</strong> I have spent one and a half days on this and tried a number of thing. In my cookie WriteCookie() method:</p>
  
  <ol>
  <li><p>Making the Cookie persistent (by setting it's expiry to tomorrow). Verified the cookie in Firefox exists and has the correct date. But once I add a value to the cookie in Controller B, the cookie has lost all it's data.</p></li>
  <li><p>Create a new cookie with the same name, added the previous values to this new cookie along with the new value. But again, navigating to another page (Controller B) and adding a value to the cookie has lost all it's previous data.</p></li>
  </ol>
  
  <p><strong>Code:</strong> Below is the original code I started with which doesn't contain the many heartbreaking attempts:</p>
  
  <pre><code>public static class CookieHelper
  {
      public static string ReadCookie(string key)
      {
          string value = string.Empty;
  
          HttpCookie cookie = HttpContext.Current.Request.Cookies["mycookie"];
          if (cookie != null)
          {
              value = HttpContext.Current.Request.Cookies["mycookie"].Values[key];
          }
  
          return value;
      }
  
      public static void WriteCookie(string key, string value)
      {
          HttpContext.Current.Response.Cookies["mycookie"].Values[key] = value;
      }
  }
  </code></pre>
  
  <p><strong>Can anyone please help and explain why the cookie values are being lost.</strong> My guess, for some unknown reason subsequent writes to the cookie AFTER a HTTP Request is creating a new cookie and overwriting the existing cookie.</p>