2015-10-18 87 views
1

我想存儲多個鍵值對。這裏是一個按鈕被點擊在Cookie中設置多個鍵值對

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; 
    } 

但是,當我再次點擊按鈕,然後提示錯誤An item with same key is already been added

回答

0

即將完成時,首次運行的代碼。使用HttpCookie.Values集合。

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); 
}