gpt4 book ai didi

c# - 无法在 asp.net mvc 中更新 cookie

转载 作者:太空狗 更新时间:2023-10-29 20:56:27 26 4
gpt4 key购买 nike

我可以写入和读取 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 值发送的 header (由 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 .

关于c# - 无法在 asp.net mvc 中更新 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com