简体   繁体   中英

set multiple key value pairs in cookie

I want to store multiple key value pairs. Here is code which works for first time when button is clicked

 Dictionary<string, string> Dic_get_Cook = new Dictionary<string, string>();
 Dic_get_Cook.Add("MyId" + itemId, "true");
 Dic_get_Cook.Add("MyAge", item["Age"].ToString());
 SetMultipleCookies("MyCookieName", Dic_get_Cook, cookie);


   public void SetMultipleCookies(string cookieName, Dictionary<string, string> dic, HttpCookie cookie)
    {

        foreach (KeyValuePair<string, string> val in dic)
        {
            cookie[val.Key] = val.Value;
        }
        cookie.Expires = DateTime.Now.AddDays(30);
        GetHttpResponse().Cookies.Add(cookie);
    }


  public static HttpResponse GetHttpResponse()
    {
        return HttpContext.Current.Response;
    }

But when i click button again then it gives error An item with same key is already been added

You're almost there. Use the HttpCookie.Values collection.

public void SetMultipleCookies(string cookieName, Dictionary<string, string> dic, HttpCookie cookie)
{

    foreach (KeyValuePair<string, string> val in dic)
    {
        cookie.Values.Add(val.Key, val.Value);
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM