c# - Cookie 更新正常,除了谷歌浏览器以外的其他浏览器
问题描述
Cookie 在所有浏览器中都可以正常更新,但在谷歌浏览器中,它无法更新 cookie。
贝娄是我的代码:
public static string CustomerName
{
get { return CookieStore.GetCookie("customername"); }
set { CookieStore.SetCookie("customername", value.ToString(), TimeSpan.FromHours(24), true); }
}
public static void SetCookie(string key, string value, TimeSpan expires, bool http = false)
{
HttpCookie encodedCookie = new HttpCookie(key, value);
// encodedCookie.HttpOnly = http;
if (HttpContext.Current.Request.Cookies[key] != null)
{
var cookieOld = HttpContext.Current.Request.Cookies[key];
cookieOld.Expires = DateTime.Now.Add(expires);
cookieOld.Value = encodedCookie.Value;
HttpContext.Current.Response.Cookies.Add(cookieOld);
}
else
{
encodedCookie.Expires = DateTime.Now.Add(expires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
}
解决方案
实际上是在SetCookie函数中发现的问题。您需要替换以下代码行
var cookieOld = HttpContext.Current.Request.Cookies[key];
在更新您的 cookie 时使用以下行。
var cookieOld = new HttpCookie(key);
Bellow 是完整的SetCookie函数。
public static void SetCookie(string key, string value, TimeSpan expires, bool http = false)
{
if (HttpContext.Current.Request.Cookies[key] != null)
{
var cookieOld = new HttpCookie(key);
cookieOld.Expires = DateTime.Now.Add(expires);
cookieOld.Value = value;
HttpContext.Current.Response.Cookies.Add(cookieOld);
}
else
{
HttpCookie encodedCookie = new HttpCookie(key, value);
encodedCookie.Expires = DateTime.Now.Add(expires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
}
推荐阅读
- java - Android 使用 MediaProjectionManager 截屏,OnImageAvailable 无法启动
- xml - SAPUI5 多重聚合绑定
- security - 如何设置 IBM Cloud App ID 的密码强度?
- git - VS Code 的 UI 中的每个 git 命令代表什么?
- javascript - 如何为Angular 5中的函数调用提供时间延迟?
- c# - 是否可以在函数结束或超出范围后重置静态字段?
- c# - 特定于类型的多个工厂函数或一个通用工厂函数然后转换为类型?
- php - 如何通过href传递(“/”)
- java - 生成的 GUID 重复,是我的 java 代码错误吗?
- javascript - jQuery .off("click") 事件不起作用