c# - 更改已存在的 cookie 的 cookie 值

标签 c# asp.net-mvc cookies

我有一个名为 SurveyCookie 的 cookie。像这样创建:

var cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
cookie.Expires = DateTime.UtcNow.AddDays(30);
Response.Cookies.Add(cookie);

这很好用。现在,当我想像这样更改“surveyPage”值时,问题就来了。

下面将创建一个新的 cookie,这不是我想要的。
int cookieValue = Convert.ToInt32(Request.Cookies["SurveyCookie"]["surveyPage"]) + 1;
Response.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();

然后我尝试了下面的这段代码,它也不起作用。当应该是 2 时,surveyPage 仍然是 1。
Request.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString(); 

由于以上都不起作用,什么会改变surveyPage的cookies值?

最佳答案

来自 ASP.NET Cookies Overview :

You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.



你可以试试这个:
HttpCookie cookie = Request.Cookies["SurveyCookie"];
if (cookie == null)
{
    // no cookie found, create it
    cookie = new HttpCookie("SurveyCookie");
    cookie.Values["surveyPage"] = "1";
    cookie.Values["surveyId"] = "1";
    cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
    cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
}
else
{
    // update the cookie values
    int newSurveyPage = int.Parse(cookie.Values["surveyPage"]) + 1;
    cookie.Values["surveyPage"] = newSurveyPage.ToString();
}

// update the expiration timestamp
cookie.Expires = DateTime.UtcNow.AddDays(30);

// overwrite the cookie
Response.Cookies.Add(cookie);

关于c# - 更改已存在的 cookie 的 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22070840/

相关文章:

node.js - Express/Passport 未为 super 测试代理设置 cookie

c# "Bad Data"解密时出现异常 - 使用 Base64 编码进行传输

c# - 在 .NET 中解析文化特定的 Decimal 和 DateTime 值

c# - Java JPanel 与 WPF XAML 中的 GridLayout 等效

c# - & 符号被 HTML 编码为 &。有什么办法可以防止这种情况?

javascript - 如何将 ajax.abort() 传播到 Controller

java - 将 Cookie 从 Java 传递到浏览器

javascript - 无法在 Promise ExpressJS 中设置响应 cookie

c# - 在 C# 中自定义反序列化示例?

asp.net-mvc - 删除@Html.TextArea的文本onclick/onfocus事件