我正在执行以下操作来设置Cookie值:
HttpCookie mycookie = new HttpCookie("mycookie");
mycookie.value = "value1";
mycookie.Expires = DateTime.Now.Add(1);
HttpContext.Current.Response.Cookies.Add(mycookie);
稍后,我会使用以下方式检查cookie:
HttpCookie mycookie = HttpContext.Current.Request.Cookies["mycookie"];
我注意到它仍有较旧的值:
mycookie.value == "oldValue"
我甚至可以在设置后立即检查cookie,并且我设置的值不在那里。它仍然是旧的价值。
正在发生的事情是该值未被设置以及如何设置它?
答案 0 :(得分:10)
试试这个,你需要删除它,然后添加它
var response = HttpContext.Current.Response;
response.Cookies.Remove("mycookie");
response.Cookies.Add(cookie);
答案 1 :(得分:0)
<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>
答案 2 :(得分:0)
当前的解决方案在 Asp.Net MVC Framework
但它在 ASP.NET Core
+
在 ASP.Net Core 中我们这样做:
HttpContext.Response.Cookies.Append("key", <value> [, <options>]);
例如,如果我想在 cookie 中存储我的名字 1 天:
HttpContext.Response.Cookies.Append("name", "Peyman", new Microsoft.AspNetCore.Http.CookieOptions {
Expires = DateTime.Now.AddDays(1),
// every othe options like path , ...
} );