Asp.Net如何把对象保存到Cookie中

  在ASP.Net中,有时候考虑到较多的使用Session来保存对象,会增加服务器的负载,所以我们会选择用Cookies来保存对象的状态,而Cookies只能保存字符串,这时,我们可以考虑用序列化操作来完成我们的目标。

  1. 引入命名空间
    1 using System.IO;
    2 using System.Runtime.Serialization;
    3 using System.Runtime.Serialization.Formatters.Binary;
  2. 将对象保存到Cookie中
     1 Person person=new Person();  //要存放的类
     2 
     3 BinaryFormatter bf=new BinaryFormatter();  //声明一个序列化类
     4 
     5 MemoryStream ms=new MemoryStream();  //声明一个内存流
     6 
     7 bf.Serialize(ms,person);  //执行序列化操作
     8 
     9 byte[] result=new byte[ms.Length];
    10 
    11 result=ms.ToArray();
    12 
    13 string temp=System.Convert.ToBase64String(result);  
    14 
    15  /*此处为关键步骤,将得到的字节数组按照一定的编码格式转换为字符串,不然当对象包含中文时,进行反序列化操作时会产生编码错误*/
    16 
    17 ms.Flush();
    18 
    19 ms.Close();
    20 
    21 HttpCookie cookie=new HttpCookie("person");  //声明一个Key为person的Cookie对象
    22 
    23 cookie.Expires=DateTime.Now.AddDays(1.0);  //设置Cookie的有效期到明天为止,此处时间可以根据需要设置
    24 
    25 cookie.Value=temp;  //将cookie的Value值设置为temp
    26 
    27 Response.Cookies.Add(cookie);
  3. 从Cookie中读取保存的对象
    1 string result=Request.Cookies["person"].Value;
    2 
    3 byte[] b=System.Convert.FromBase64String(result);  //将得到的字符串根据相同的编码格式分成字节数组
    4 
    5 MemoryStream ms=new MemoryStream(b,0,b.Length);  //从字节数组中得到内存流
    6 
    7 BinaryFormatter bf=new BinaryFormatter();
    8 
    9 Person person=bf.Deserialize(ms) as Person;  //反序列化得到Person类对象

posted on 2014-08-12 10:47  Noker  阅读(542)  评论(0编辑  收藏  举报

导航