31

I'm doing the following to set a cookie value:

HttpCookie mycookie = new HttpCookie("mycookie");
mycookie.Value = "value1";  // Case sensitivity
mycookie.Expires = DateTime.Now.Add(1);
HttpContext.Current.Response.Cookies.Add(mycookie);

Sometime later, I check the cookie using:

HttpCookie mycookie = HttpContext.Current.Request.Cookies["mycookie"];

I notice it still has an older value:

mycookie.Value == "oldValue"

I can even check the cookie immediately after setting it and the value I've set isn't there. It's still the old value.

What is happening that the value isn't being set and how can I set it???

MikeRyz
  • 209
  • 1
  • 3
  • 18
4thSpace
  • 43,672
  • 97
  • 296
  • 475

3 Answers3

31

Try this, you need to remove it and then add it

var response = HttpContext.Current.Response;
response.Cookies.Remove("mycookie");
response.Cookies.Add(cookie);
eric_eri
  • 699
  • 11
  • 19
0

The current solution works fine in the Asp.Net MVC Framework
but It doesn't work in ASP.NET Core+

In the ASP.Net Core We do like this:

HttpContext.Response.Cookies.Append("key", <value> [, <options>]);

for example if I want to store my name in cookie for 1 day:

HttpContext.Response.Cookies.Append("name", "Peyman", new Microsoft.AspNetCore.Http.CookieOptions { 
             Expires = DateTime.Now.AddDays(1),
             // every othe options like path , ...
            } );
Peyman Majidi
  • 1,777
  • 2
  • 18
  • 31
-6

<script type="text/javascript">
<!--
function WriteCookie()
{
    if(document.myform.customer.value==""){
    alert("Enter some value!");
    return;
    }
    cookievalue=escape(document.myform.costomer.value)+";";
    document.cookie="name="+cookievalue;
    document.write("Setting Cookies:"+"name="+cookievalue);

}
//-->
</script>
</head>
<body>
<form name="myform" action="cook.html">
Enter name:<input type="text" name="customer"/>
<input type="button" value="set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>