简体   繁体   中英

How to set cookie value?

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

HttpCookie mycookie = new HttpCookie("mycookie");
mycookie.value = "value1";
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?

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

var response = HttpContext.Current.Response;
response.Cookies.Remove("mycookie");
response.Cookies.Add(cookie);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM