I just came across this exact scenario with a similar block of code:
public ActionResult Index(int requestValue) { var name = "testCookie"; var oldVal = Request.Cookies[name] != null ? Request.Cookies[name].Value : null; var val = (!String.IsNullOrWhiteSpace(oldVal) ? oldVal + ";" : null) + requestValue.ToString(); var cookie = new HttpCookie(name, val) { HttpOnly = false, Secure = false, Expires = DateTime.Now.AddHours(1) }; HttpContext.Response.Cookies.Set(cookie); return Content("Cookie set."); }
The first time you run the cookie, it will be set without incident. But any subsequent run will never update it at all (value or expiration).
It turns out that the semicolon is an illegal character in the cookie value, and trying to differentiate your values ββwith this will truncate the cookie value. If we change the half-deck to another character, like a pipe (|), everything will be fine.
Consider the header sent for the cookie value (courtesy of Fiddler):
The response sent 61 bytes of cookie data:
Set-Cookie: testCookie = 2; 1; expires = Tue, 09-Sep-2014 19:23:43 GMT; Path = /
As we can see, a colon is used to separate parts of the cookie definition. Thus, if you want to use the half-line in the cookie itself, it must be encoded so as not to be misinterpreted. This answer gives a more detailed overview of the actual specification: fooobar.com/questions/28819 / ....
source share