我有一个名为 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值?
最佳答案
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/