这个是刚写的操作类
public static class CookieHelper
{
public static void CreateCookie(string cookieName, DateTime dateTime)
{
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Expires = dateTime;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public static void CreateCookie(string cookieName)
{
CreateCookie(cookieName, DateTime.Now.AddDays(1));
}
public static void AddKey(string cookieName, string keyName, string keyVal)
{
if (HttpContext.Current.Request.Cookies[cookieName] == null) CreateCookie(cookieName);
HttpContext.Current.Response.Cookies[cookieName][keyName] = keyVal;
}
public static void DeleteKey(string cookieName, string keyName)
{
HttpContext.Current.Response.Cookies[cookieName].Values.Remove(keyName);
}
public static string GetKey(string cookieName, string keyName)
{
if (HttpContext.Current.Request.Cookies[cookieName] != null)
{
if (HttpContext.Current.Request.Cookies[cookieName][keyName] != null)
{
return HttpContext.Current.Request.Cookies[cookieName][keyName] as string;
}
}
return string.Empty;
}
}
有两个页面 1.aspx 和 2.aspx
当在 1.aspx 执行
AddKey("test", "aa", "1");
AddKey("test", "bb", "2");
aa=1&bb=2
正确的。
当在 2.aspx 执行
AddKey("test", "cc", "3");
AddKey("test", "dd", "4");
返回的 Cookie 值是
cc=3&dd=4
1.aspx 和 2.aspx 的Cookie值无法叠加。测试多次还是找不到结果,请指教。。