更改已存在的cookie的cookie值

时间:2014-02-27 14:02:47

标签: 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();

然后我尝试下面的代码也不起作用。调查页仍然是1,应该是2。

Request.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString(); 

由于以上两种方法都没有改变surveyPage的cookie值吗?

3 个答案:

答案 0 :(得分:35)

来自ASP.NET Cookies Overview

  

您无法直接修改Cookie。相反,更改cookie   包括用新值创建一个新的cookie,然后发送   cookie到浏览器覆盖客户端上的旧版本。

你可以试试这个:

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);

答案 1 :(得分:7)

每次需要修改现有cookie时,都应始终创建一个新cookie,以下对我有用:

var cookie = new System.Web.HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] =  newValue;
cookie.Expires = DateTime.Now.AddDays(1000);
cookie.SameSite = System.Web.SameSiteMode.None;
cookie.Secure = true;
this.HttpContext.Response.Cookies.Add(cookie);

答案 2 :(得分:-1)

查看Response.SetCookie()方法,因为这会设置更新您现有的Cookie