在cookie中设置多个键值对
本文关键字:键值对 设置 cookie | 更新日期: 2023-09-27 18:18:17
我想存储多个键值对。以下是第一次点击按钮
时工作的代码 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
你就快成功了。使用HttpCookie。值集合。
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);
}