【问题标题】:Cookie update fine other browser except google chromeCookie 更新正常,除了谷歌浏览器以外的其他浏览器
【发布时间】:2021-01-03 22:35:34
【问题描述】:

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.net cookies setcookie


    【解决方案1】:

    其实是在SetCookie函数中发现的问题。您需要替换以下代码行

    var cookieOld = HttpContext.Current.Request.Cookies[key];
    

    在更新您的 cookie 时使用以下行。

    var cookieOld = new HttpCookie(key);
    

    下面是完整的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);
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 2011-03-28
      • 2012-07-31
      • 1970-01-01
      • 2013-03-27
      • 2016-07-13
      • 2017-11-24
      相关资源
      最近更新 更多