更改已存在的 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();
然后我尝试了下面的这段代码,但它也不起作用.当应该是 2 时,surveyPage 仍然是 1.
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 的cookies 值?
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屋!