无法检索cookie值

时间:2013-12-17 06:54:10

标签: c# asp.net-mvc-4 cookies

使用编码存储和检索cookie

public static void SetCookie(string key, string value, int dayExpires)
    {
        HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));
        encodedCookie.Expires = DateTime.Now.AddDays(dayExpires);

        HttpContext.Current.Response.Cookies.Remove(key);
        HttpContext.Current.Response.Cookies.Add(encodedCookie);
    }
    public static string GetCookie(string key)
    {
        string value = string.Empty;
        HttpCookie cookie = HttpContext.Current.Request.Cookies[key];

        if (cookie != null)
        {
            // For security purpose, we need to encrypt the value.
            HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
            value = decodedCookie.Value;
        }
        else
        {
            SetCookie("currency", "GBP", 1);
            if (key.ToUpper() == "CURRENCY")
                value = "GBP";
            else if (key.ToUpper() == "COUNTRYCODE")
                value = "GB";
        }
        return value;
    }

}

能够存储cookie,并且当我尝试使用HttpContext.Current.Request.Cookies[key]来获取cookie中的货币值时,其中key具有货币,其值为“”

在下图中,您可以查看存储的Cookie cookie quick watch

在这里你可以看到你可以重复两次货币。在密钥[4]中,货币是“”,因为我在密钥[6]中有我的cookie值。当我删除密钥然后在直接行中添加密钥时,为什么货币重复两次的任何帮助。

出于测试目的,我已经放置了该组并立即进入。代码

CookieStore.SetCookie("currency", CurrencyCode, 1);
string currencycookie=CookieStore.GetCookie("currency");

最终我必须只有一种货币,我有唯一的钥匙。

感谢。

1 个答案:

答案 0 :(得分:1)

删除这样的密钥对您没有帮助,删除客户端浏览器中设置的cookie。您必须为现有密钥设置过去的到期日期。更好的解决方案是检查密钥是否可用,更新cookie的值,而不是删除并添加它。

      if (Request.Cookies[key] != null)
        {
            Response.Cookies[key].Value = "NEW VAalue"                
        }
        else
         // create the new cookie key.

请参阅我的更新代码,其中包含删除和添加新值的逻辑

      if (Request.Cookies["Test"] == null)
        {
            HttpCookie testCookie = new HttpCookie("Test");
            testCookie.Value = "1";
            testCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(testCookie);
        }
        else
        {
            var c = Request.Cookies["Test"];
            c.Expires = DateTime.Now.AddDays(-10);
            Response.Cookies.Add(c);
            HttpCookie testCookie = new HttpCookie("Test");
            testCookie.Value = "2";
            testCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(testCookie);
        }

我已更新您的方法。

      public static void SetCookie(string key, string value, int dayExpires)
    {
        if (Request.Cookies[key] != null)
        {
            var c = HttpContext.Current.Request.Cookies[key];
            c.Expires = DateTime.Now.AddDays(-10);
            HttpContext.Current.Response.Cookies.Add(c);
        }
        HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));
        encodedCookie.Expires = DateTime.Now.AddDays(dayExpires);
        HttpContext.Current.Response.Cookies.Add(encodedCookie);
    }