Change a cookie value of a cookie that already exists
You should always create a new cookie each time you need to modify an existing one , the following works for me :
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);
From 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.
You can try this:
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);