如何设置cookie值

本文关键字:cookie 设置 何设置 | 更新日期: 2023-09-27 18:20:56

我正在执行以下操作来设置cookie值:

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

一段时间后,我使用检查cookie

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

我注意到它仍然有一个旧的价值:

mycookie.Value == "oldValue"

我甚至可以在设置cookie后立即检查它,但我设置的值不在那里。它仍然是旧的价值观。

如果没有设置值,会发生什么情况?我如何设置它???

如何设置cookie值

试试这个,你需要删除它,然后添加

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

当前解决方案在Asp.Net MVC Framework中运行良好
但它在ASP.NET Core+中不起作用

在ASP.Net核心中,我们喜欢这样:

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

例如,如果我想在cookie中存储我的名字一天:

HttpContext.Response.Cookies.Append("name", "Peyman", new Microsoft.AspNetCore.Http.CookieOptions { 
             Expires = DateTime.Now.AddDays(1),
             // every othe options like path , ...
            } );

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