改变已存在的cookie的cookie值 [英] Change a cookie value of a cookie that already exists
问题描述
我有一个名为SurveyCookie的cookie。创建像这样:
I have a cookie called SurveyCookie. Created like so:
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像这样。
Which works great. Now the problem comes when I want to change the value "surveyPage" like so.
下面将创建一个新的Cookie这是不是我想要的。
The below will create a new cookie which is not what I want.
int cookieValue = Convert.ToInt32(Request.Cookies["SurveyCookie"]["surveyPage"]) + 1;
Response.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
然后我尝试这个code以下不工作的。该surveyPage仍为1时,它应该是2。
Then I tried this code below which doesn't work either. The surveyPage is still 1 when it should be 2.
Request.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
由于上述两个工程是什么改变饼干值surveyPage?
Since neither of the above works what does change the cookies value for surveyPage?
推荐答案
您不能直接修改的cookie。相反,改变一个cookie
包括创建新值的新的cookie,然后发送的
cookie发送到浏览器来覆盖客户端上的旧版本。
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);
这篇关于改变已存在的cookie的cookie值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!