Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>对象的序列化和反序列化</title>
</head>
<body>
<form id="form1" runat="server">
用户ID: <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox><br />
用户名: <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
用户生日: <asp:TextBox ID="txtAge" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSerializeToCookies" runat="server" Text="序列化" OnClick="btnSerializeToCookies_Click" />
<asp:Button ID="btnDeserializeByCookies" runat="server" Text="反序列化" OnClick="btnDeserializeByCookies_Click" /><br />
<asp:Label ID="lblShow" runat="server" Width="210px"></asp:Label>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace WebApplication1
{
/* gdjlc 2009年12月14日 */
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//定义序列化的类时必须加上[Serializable]属性
[Serializable]
public class User : IDeserializationCallback
{
public User(int userID, string userName, DateTime birthDay)
{
this.userID = userID;
this.userName = userName;
this.birthDay = birthDay;
}
private int userID;
private string userName;
private DateTime birthDay;
[NonSerialized]
private int age; //年龄依赖于生日,不参与序列化
/// <summary>
/// 用户ID
/// </summary>
public int UserID
{
get { return userID; }
set { userID = value; }
}
/// <summary>
/// 用户名
/// </summary>
public string UserName
{
get { return userName; }
set { userName = value; }
}
/// <summary>
/// 生日
/// </summary>
public DateTime BirthDay
{
get { return birthDay; }
set { birthDay = value; }
}
/// <summary>
/// 年龄
/// </summary>
public int Age
{
get { return age; }
set { age = value; }
}
//反序列化完成时自动调用这一方法
void IDeserializationCallback.OnDeserialization(object sender)
{
age = DateTime.Now.Year - birthDay.Year;
}
}
//写入Cookies
protected void btnSerializeToCookies_Click(object sender, EventArgs e)
{
User user = new User(int.Parse(txtUserID.Text), txtUserName.Text, Convert.ToDateTime(txtAge.Text));
Response.Cookies["User"].Value = SerializeObj(user);
Response.Cookies["User"].Expires = DateTime.Now.AddMinutes(30);
}
//从Cookies中读取
protected void btnDeserializeByCookies_Click(object sender, EventArgs e)
{
if (Request.Cookies["User"] != null)
{
User user = DeserializeObj(Request.Cookies["User"].Value);
lblShow.Text = user.UserID + "-" + user.UserName + "-" + user.BirthDay + "-" + user.Age;
}
}
// 序列化对象
public static string SerializeObj(User user)
{
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, user);
return Convert.ToBase64String(ms.ToArray());
}
}
// 反序列化对象
public static User DeserializeObj(string str)
{
byte[] buf = Convert.FromBase64String(str);
using (MemoryStream ms = new MemoryStream(buf))
{
IFormatter formatter = new BinaryFormatter();
User user = formatter.Deserialize(ms) as User;
return user;
}
}
}
}