C# 无法在asp.net mvc中更新Cookie
我可以写入和读取cookie,但我不能更改现有cookie的值,因为它始终具有第一个设置值。我找到了一些方法来实现它,但没有一个可行。这是我的密码:C# 无法在asp.net mvc中更新Cookie,c#,asp.net-mvc,cookies,C#,Asp.net Mvc,Cookies,我可以写入和读取cookie,但我不能更改现有cookie的值,因为它始终具有第一个设置值。我找到了一些方法来实现它,但没有一个可行。这是我的密码: private void AddPost(string key) { var context = System.Web.HttpContext.Current; var request = context.Request; var response = context.Response;
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);
}
}
根据cookie,文件应该是owerwrite
每个cookie必须有一个唯一的名称,以便以后从浏览器中读取时可以识别。由于Cookie是按名称存储的,因此将两个Cookie命名为同一名称将导致其中一个被覆盖
你知道如何修复它吗?你不能直接修改cookie。相反,您正在创建一个新的cookie来覆盖旧的cookie。 试一试 这将更改客户端响应,而不是服务器请求
要使用Response.AppendCookie,首先必须从Cookie集合中获取一个HttpCookie。我刚刚遇到了一个类似的代码块:
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提供):
响应发送了61字节的Cookie数据:
设置Cookie:testCookie=2;1.expires=2014年9月9日星期二19:23:43 GMT;路径=/
正如我们所看到的,分号用于分隔cookie定义的各个部分因此,如果您想在cookie值本身中使用分号,则必须对其进行编码,以免被误解。此答案更详细地介绍了实际的规范:。您不能使用分号(纯文本)作为分隔符 根据古老的Netscape cookie_规范: 此字符串是一个字符序列,不包括分号、逗号和空格
它不起作用。正如我在问题中所写的,我已经试过了。这个解决方案对这个问题无效。我有完全相同的问题。完全令人困惑。
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.");
}