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.
What's working: 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.
Problem: 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.
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.
Investigations: I have spent one and a half days on this and tried a number of thing. In my cookie WriteCookie() method:
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.
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.
Code: Below is the original code I started with which doesn't contain the many heartbreaking attempts:
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;
}
}
Can anyone please help and explain why the cookie values are being lost. 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.