c# - Cookie 未更新

标签 c# cookies

我正在尝试更新 cookie 值,但它不起作用 - 我尝试的所有操作都没有更新 cookie,我总是得到 cookie 的初始值。

所以我进行了搜索,根据 MSDN,我应该能够通过执行以下操作来更新 cookie:

HttpCookie cookie = new HttpCookie("cookiename");
cookie.Value = cookieValue;
cookie.Expires = DateTime.Now.AddDays(30);
HttpContext.Current.Response.Cookies.Set(cookie); // also just tried using .Add again here

因为这行不通,我又进行了一次搜索,SO 上的人说我应该可以这样做:

HttpContext.Current.Response.Cookies["cookiename"].Value = cookieValue;
HttpContext.Current.Response.Cookies["cookiename"].Expires = DateTime.Now.AddDays(30);

但这也不起作用,所以我尝试删除 cookie 并重新添加它:

HttpCookie cookie = new HttpCookie("cookiename");
cookie.Value = cookieValue;
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);

cookie.Expires = DateTime.Now.AddDays(30);
HttpContext.Current.Response.Cookies.Add(cookie);

在重新添加之前,我还尝试使用以下方法删除 cookie

ResponseCookies.Remove("cookiename");

这也没有用,所以我现在不确定还能尝试什么。有谁知道如何用 c# 更新 cookie?

更新

如果我单步执行代码并在更新后检查 HttpContext.Current.Request.Cookies["cookiename"].Value,它会显示新值。如果我然后回收应用程序池以便必须再次从文件中读取 cookie,它会显示原始值,因此上面的代码似乎没有更新物理 cookie

最佳答案

你不能!

根据 MSDN ,您已将当前 cookie 替换为同名的新 cookie。关于这个有一整节。

Modifying and Deleting Cookies

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.


更新

在评论中写完后,我们发现了这里的问题。

根据 specs,您也不得在 cookie 值中使用分号。 .

This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required.

关于c# - Cookie 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912581/

相关文章:

c# - ILogger 未将 TRACE 和 DEBUG 消息写入目标

c# - Excel 中的混合数据类型,IMEX 不起作用

C# WPF 参数异常 : Specified Visual is already a child of another Visual or the root of a CompositionTarget

c# - 使用 Redis ServiceStack 的事务时如何创建多个序列号

http - 打包的 cookie 应该被视为单个 cookie 吗?

ruby-on-rails - 在 Rails 应用程序中跟踪唯一身份访问者 - session 还是显式 cookie?

c# - 清除 WebView 中的所有 cookie

c# - 一种选择特定随机名称的方法

javascript - ASP.NET Core 中无法正确读取 Cookie

javascript - JQuery Cookie 1 分钟后过期