我可以写和读cookie但我不能改变现有cookie的值,它总是有第一个设定值.我发现几乎没有办法可以实现,但没有人工作.这是我的代码:
private void AddPost(string key) { var context = System.Web.HttpContext.Current; var request = context.Request; var response = context.Response; var cookie = request.Cookies[Constants.PostsViewing]; if (cookie == null || string.IsNullOrEmpty(cookie.Value)) { response.Cookies.Add(new HttpCookie(Constants.PostsViewing,key) { Expires = DateTime.Now.AddDays(365) }); } else { if (cookie.Value.Split(';').Contains(key)) { return; } var v = cookie.Value + ";" + key; cookie.Value = v; cookie.Expires = DateTime.Now.AddDays(365); response.Cookies.Add(cookie); // this way also doesn't work //cookie.Value = v; //response.AppendCookie(cookie); // and this //response.Cookies[Constants.PostsViewing].Value = v; //response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365); } }
根据msdn cookie文件应该是owerwritten.
Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name,naming two cookies the same will cause one to be overwritten.
你知道怎么解决它吗?
解决方法
我刚刚使用类似的代码块遇到了这个确切的场景:
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."); }
代码第一次运行时,cookie将被设置而不会发生意外.但任何后续运行都不会更新它(值或到期).
事实证明,分号是cookie值中的非法字符,并且尝试用它来分隔您的值将导致cookie值被截断.如果我们将分号更改为另一个字符,比如管道(|),那么一切都很好.
考虑为cookie值发送的标头(由Fiddler提供):
Response sent 61 bytes of Cookie data:
Set-Cookie: testCookie=2;1; expires=Tue,09-Sep-2014 19:23:43 GMT; path=/
我们可以看到,分号用于分隔cookie定义的各个部分.因此,如果要在cookie值本身中使用分号,则必须对其进行编码,以免误解.这个答案给出了更详细的实际规格:https://stackoverflow.com/a/1969339/143327.