ASP.Net如何用Cookies保存对象

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

引入的命名空间 

 

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

将对象保存到Cookie中。

Person person=new Person(); //要存放的类

BinaryFormatter bf
=new BinaryFormatter(); //声明一个序列化类

MemoryStream ms
=new MemoryStream(); //声明一个内存流

bf.Serialize(ms,person);
//执行序列化操作

byte[] result=new byte[ms.Length];

result
=ms.ToArray();

string temp=System.Convert.ToBase64String(result);

/*此处为关键步骤,将得到的字节数组按照一定的编码格式转换为字符串,不然当对象包含中文时,进行反序列化操作时会产生编码错误*/

ms.Flush();

ms.Close();

HttpCookie cookie
=new HttpCookie("person"); //声明一个Key为person的Cookie对象

cookie.Expires
=DateTime.Now.AddDays(1.0); //设置Cookie的有效期到明天为止,此处时间可以根据需要设置

cookie.Value
=temp; //将cookie的Value值设置为temp

Response.Cookies.Add(cookie);

从Cookie中取出保存的对象值

string result=Request.Cookies["person"].Value;

byte[] b=System.Convert.FromBase64String(result); //将得到的字符串根据相同的编码格式分成字节数组

MemoryStream ms
=new MemoryStream(b,0,b.Length); //从字节数组中得到内存流

BinaryFormatter bf
=new BinaryFormatter();

Person person
=bf.Deserialize(ms) as Person; //反序列化得到Person类对象

 转载:网上

posted on 2011-03-31 13:46  卡域克  阅读(4218)  评论(1)    收藏  举报