将对象保存在cookise中

 1   /// <summary>
 2     /// 存储历史记录到cookise中
 3     /// </summary>
 4     /// <param name="history"></param>
 5     /// <returns></returns>
 6     public static bool SaveHistoryCookies(List<HistoryEntity> history)
 7     {
 8         try
 9         {
10 
11             BinaryFormatter bf = new BinaryFormatter();  //声明一个序列化类
12 
13             MemoryStream ms = new MemoryStream();  //声明一个内存流
14 
15             bf.Serialize(ms, history);  //执行序列化操作
16 
17             byte[] result = new byte[ms.Length];
18 
19             result = ms.ToArray();
20 
21             string temp = System.Convert.ToBase64String(result);
22 
23             /*此处为关键步骤,将得到的字节数组按照一定的编码格式转换为字符串,不然当对象包含中文时,进行反序列化操作时会产生编码错误*/
24 
25             ms.Flush();
26 
27             ms.Close();
28 
29             HttpCookie cookie = new HttpCookie("history");  //声明一个Key为person的Cookie对象
30 
31             cookie.Expires = DateTime.Now.AddDays(30.0);  //设置Cookie的有效期,此处时间可以根据需要设置
32 
33             cookie.Value = temp;  //将cookie的Value值设置为temp
34             System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
35 
36             return true;
37         }
38         catch (Exception ex)
39         {
40             return false;
41         }
42     }
 1  /// <summary>
 2     /// 读取历史记录
 3     /// </summary>
 4     /// <returns></returns>
 5     public static List<HistoryEntity> ReadHistoryCookies()
 6     {
 7         try
 8         {
 9             string result = System.Web.HttpContext.Current.Request.Cookies["history"].Value;
10 
11             byte[] b = System.Convert.FromBase64String(result);  //将得到的字符串根据相同的编码格式分成字节数组
12 
13             MemoryStream ms = new MemoryStream(b, 0, b.Length);  //从字节数组中得到内存流
14 
15             BinaryFormatter bf = new BinaryFormatter();
16 
17             return bf.Deserialize(ms) as List<HistoryEntity>;  //反序列化得到history类对象
18         }
19         catch (Exception)
20         {
21 
22             return null;
23         }
24 
25 
26     }
原文地址:https://www.cnblogs.com/lollipop/p/2730939.html