ASP.NET通过序列化将对象保存到Cookies

  • Post author:
  • Post category:其他



http://www.51testing.com/html/02/n-185402.html


思路:

一、将对象序列化为字符串

二、将序列化后的对象保存到Cookies/Session中

三、读取保存在Cookies/Session中的字符串

四、反序列化,将其还原为对象


实现:

(1)一个对象要序列,必须在类定义的时候,加上[Serializable]特性

(2)为了避免处理中文时的异常,先将其编码为Base64,再存储到Cookies/Session中

using System;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

using System.Collections.Generic;

namespace Com.LoRui

{


public class LoRuiTester

{


public static void Main()

{


//用于



测试



的一个User实例。注意,这里用了C# 3.0的新语法

User user = new User

{


UserName = “LoRui”,

Password = “1234567″,

RealName = “龙睿”,

LoginTimes = 32

};

//序列化

string user2str = Serializer.SerializeObject(user);

Console.WriteLine(user2str);

保存到Cookies

//HttpContext.Current.Response.Cookies[COOKIES_NAME].Value = user2str;

//反序列化

string str = user2str;

从Cookies读取

//str = HttpContext.Current.Request.Cookies[COOKIES_NAME].Value;

User str2user = Serializer.DeserializeObject(str);

Console.WriteLine(”UserName: {0}, Password: {1}, RealName: {2}, LoginTimes: {3}”,

str2user.UserName,

str2user.Password,

str2user.RealName,

str2user.LoginTimes);

Console.ReadKey();

}

}

[Serializable]

public class User

{


//以下均为User类的属性,使用了C# 3.0的新语法

public string UserName{get;set;}

public string Password{get;set;}

public string RealName{get;set;}

public int LoginTimes{get;set;}

}

public static class Serializer

{


public static string SerializeObject(T obj)

{


System.Runtime.Serialization.IFormatter bf = new BinaryFormatter();

string result = string.Empty;

using(System.IO.MemoryStream ms = new System.IO.MemoryStream())

{


bf.Serialize(ms, obj);

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

byt = ms.ToArray();

result = System.Convert.ToBase64String(byt);

ms.Flush();

}

return result;

}

public static T DeserializeObject(string str)

{


T obj;

System.Runtime.Serialization.IFormatter bf = new BinaryFormatter();

byte[] byt = Convert.FromBase64String(str);

using(System.IO.MemoryStream ms = new System.IO.MemoryStream(byt,0,byt.Length))

{


obj = (T)bf.Deserialize(ms);

}

return obj;

}

}

}