首页 > 解决方案 > 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);
    }
}

标签: c#asp.netcookiessetcookie

解决方案


实际上是在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);
            }
        }

推荐阅读