ASP.NET实例:利用对象序列化将购物车保存在Cookie中_[Asp.Net教程]                                           					
ASP.NET实例:利用对象序列化将购物车保存在Cookie中
购物车类:ShopCart.cs(说明:主要利用hashtable保存商品对象)
using System;
using System.Collections;
/// 
/// 购物车类
/// [Serializable]
public class ShopCart
{
    public Hashtable _CartItems = new Hashtable();
    /// 
    /// 构造函数
    ///     public ShopCart()
    {
        ///to do something
    }
    /// 
    /// 返回购物车中的所有商品(接口类型)
    ///     public ICollection CartItems
    {
        get { return _CartItems.Values; }
    }
    /// 
    /// 购物中所有商品的价格合计
    ///     public double Total
    {
        get
        {
            double sum = 0;
            foreach (ShopCartItem item in _CartItems.Values)
            {
                sum += ((item.Price * item.Quantity) + item.SendPrice);
            }
            return sum;
        }
    }
    /// 
    /// 返回购物车里所有商品的数量
    ///     public double TotalNum
    {
        get
        {
            double sum = 0;
            foreach (ShopCartItem item in _CartItems.Values)
            {
                sum += item.Quantity;
            }
            return sum;
        }
    }
    /// 
    /// 向购物车里添加某商品
    ///     /// 
商品ID
    /// 
商品名称
    /// 
商品单价
    /// 
如果购物车中已经存在该商品,该商品的数量是否加一,True数量加1,False数量不变
    public void AddItem(string ID, string Name, string DeliveryName, double Price, int Score, string ProductId, string PicUrl, double MarketPrice, double UserPrice, double VipPrice, double SendPrice,string ShopID, string UrlFrom, bool AutoAddQuantity)
    {
        ShopCartItem item = (ShopCartItem)_CartItems[ID];
        if(item == null)
            _CartItems.Add(ID, new ShopCartItem(ID, Name, DeliveryName, Price, Score, ProductId, PicUrl, MarketPrice, UserPrice, VipPrice, SendPrice,ShopID, UrlFrom));
        else
        {
            if(AutoAddQuantity)
            {
                item.Quantity++;
            }
            _CartItems[ID] = item;
        }
    }
    /// 
    /// 从购物车里移除某商品
    ///     /// 
商品ID
    /// 
如果商品数量大于1,是否彻底从购物车中删除该种商品,true彻底从购物车中删除该种商品,false则仅将该种商品数量减一
    public void RemoveItem(string ID, bool FullDelete)
    {
        ShopCartItem item = (ShopCartItem)_CartItems[ID];
        if(item == null)
        {
            return;
        }
        else
        {
            if(FullDelete)
            {
                _CartItems.Remove(ID);
            }
            else
            {
                item.Quantity--;
                if(item.Quantity == 0)
                {
                    _CartItems.Remove(ID);
                }
                else
                {
                    _CartItems[ID] = item;
                }
            }
        }
    }
    /// 
    /// 修改购物车里某商品的数量
    ///     /// 
商品ID
    /// 
商品数量
    public void UpdateItem(string ID, int Quantity)
    {
        ShopCartItem item = (ShopCartItem)_CartItems[ID];
        if(item == null)
        {
            return;
        }
        else
        {
            if(Quantity > 0) //商品数量必须大于0
            {
                item.Quantity = Quantity;
            }
            _CartItems[ID] = item;
        }
    }
    /// 
    /// 清空购物车
    ///     public void ClearCart()
    {
        _CartItems.Clear();
    }
}
/// 
/// [购物车具体]商品类
/// [Serializable]
public class ShopCartItem
{
    private string _ID;//产品GUID
    private string _Name;//产品名称
    private string _DeliveryName;//物流产品名
    private double _Price=0;//产品单价(结算价格)
    private int _Score = 0;//产品单个积分
    private int _Quantity = 1;//产品数量
    private string _ProductId;//产品自定义编号
    private string _PicUrl;//图片地址
    private double _MarketPrice=0;//市场价格
    private double _VipPrice=0;//VIp价格
    private double _UserPrice=0;//会员价格
    private double _SendPrice=0;//运输费用
    private string _ShopID;//商家ID
    private string _UrlFrom; //页面来源
    /// 
    /// 属性:商品ID
    ///     public string ID
    {
        get { return _ID; }
    }
    /// 
    /// 属性:商品名称Name
    ///     public string Name
    {
        get { return _Name; }
    }
    /// 
    /// 属性:商品单价Price
    ///     public double Price
    {
        get { return _Price; }
    }
    /// 
    /// 单件产品所获积分
    ///     public int Score
    {
        get
        {
            return _Score;
        }
        set
        {
            _Score = value;
        }
    }
    /// 
    /// 产品编号
    ///     public string ProductId
    {
        get
        {
            return _ProductId;
        }
        set
        {
            _ProductId = value;
        }
    }
    /// 
    /// 产品图片地址
    ///     public string PicUrl
    {
        get
        {
            return _PicUrl;
        }
        set
        {
            _PicUrl = value;
        }
    }
    /// 
    /// 市场价格
    ///     public double MarketPrice
    {
        get
        {
            return _MarketPrice;
        }
        set
        {
            _MarketPrice = value;
        }
    }
    /// 
    /// VIP价格
    ///     public double VipPrice
    {
        get
        {
            return _VipPrice;
        }
        set
        {
            _VipPrice = value;
        }
    }
    /// 
    /// 会员价格
    ///     public double UserPrice
    {
        get
        {
            return _UserPrice;
        }
        set
        {
            _UserPrice = value;
        }
    }
    /// 
    /// 运输费用
    ///     public double SendPrice
    {
        get
        {
            return _SendPrice;
        }
        set
        {
            _SendPrice = value;
        }
    } 
    /// 
    /// 属性:商品数量Quantity
    ///     public int Quantity
    {
        get { return _Quantity; }
        set { _Quantity = value; }
    }
    /// 
    /// 商家ID
    ///     public string ShopID {
        get { return _ShopID; }
        set { _ShopID = value; }
    }
    /// 
    /// 页面来源
    ///     public string UrlFrom
    {
        get { return _UrlFrom; }
        set { _UrlFrom = value; }
    }
    /// 
    /// 购物车商品项完整构架函数
    ///     /// 
产品ID
    /// 
产品名称
    /// 
产品物流名称
    /// 
产品单价(计算价)
    /// 
产品积分
    /// 
产品编号
    /// 
产品图片
    /// 
会员价格
    /// 
市场价格
    /// 
VIp价格
    /// 
运输费用
    /// 
商家ID
    /// 
页面来源
    public ShopCartItem(string ID, string Name, string DeliveryName, double Price, int Score, string ProductId, string PicUrl, double MarketPrice, double UserPrice, double VipPrice, double SendPrice, string ShopID, string UrlFrom)
    {
        _ID = ID;
        _Name = Name;
        _DeliveryName = DeliveryName;
        _Quantity = 1;
        _Price = Price;
        _Score = Score;
        _ProductId = ProductId;
        _PicUrl = PicUrl;
        _MarketPrice = MarketPrice;
        _UserPrice = UserPrice;
        _VipPrice = VipPrice;
        _SendPrice = SendPrice;
        _ShopID = ShopID;
        _UrlFrom = UrlFrom;
    }
    /// 
    /// 购物车商品项简单构架函数
    ///     /// 
产品ID
    /// 
产品名称   
    /// 
产品单价(计算价)
    public ShopCartItem(string ID, string Name, double Price)
    {
        _ID = ID;
        _Name = Name;
        _DeliveryName = "";
        _Quantity = 1;
        _Price = Price;
        _Score = 0;
        _ProductId = "";
        _PicUrl = "";
        _MarketPrice = 0;
        _UserPrice = 0;
        _VipPrice = 0;
        _SendPrice = 0;
        _ShopID = "";
        _UrlFrom = "";
    }
    /// 
    /// 购物车商品项构架函数
    ///     /// 
产品ID
    /// 
产品名称   
    /// 
产品单价(计算价)
    /// 
页面来源
    public ShopCartItem(string ID, string Name, double Price,string UrlFrom)
    {
        _ID = ID;
        _Name = Name;
        _DeliveryName = "";
        _Quantity = 1;
        _Price = Price;
        _Score = 0;
        _ProductId = "";
        _PicUrl = "";
        _MarketPrice = 0;
        _UserPrice = 0;
        _VipPrice = 0;
        _SendPrice = 0;
        _ShopID = "";
        _UrlFrom = UrlFrom;
    }
    /// 
    /// 购物车商品项标准构架函数
    ///     /// 
产品ID
    /// 
产品名称   
    /// 
产品单价(计算价)
    /// 
页面来源
    /// 
页面来源
    public ShopCartItem(string ID, string Name, double Price,string ShopID, string UrlFrom)
    {
        _ID = ID;
        _Name = Name;
        _DeliveryName = "";
        _Quantity = 1;
        _Price = Price;
        _Score = 0;
        _ProductId = "";
        _PicUrl = "";
        _MarketPrice = 0;
        _UserPrice = 0;
        _VipPrice = 0;
        _SendPrice = 0;
        _ShopID = ShopID;
        _UrlFrom = UrlFrom;
    }
} 
测试页面:Demo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Public_Test_Demo" %>    
无标题页    后置代码Demo.aspx.cs文件:
using System;
using System.Collections;
using System.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Text;
using CNTVS.TOOLS;
public partial class Public_Test_Demo : System.Web.UI.Page
{
    string CookieName = "ShopCart";
    protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
        {
            ShopCart SC = new ShopCart();
            SC.AddItem("1", "ProductName", "ProductName", 0, 0, "ProductID", "", 0, 0, 0, 0, "ShopId", "TestUrl", true);
            SC.AddItem("2", "ProductName123", "ProductName123", 0, 0, "ProductID123", "", 0, 0, 0, 0, "ShopId111", "TestUrl23", true);
            //将ShopCart对象写入Cookie
            IFormatter fm = new BinaryFormatter();           
            Stream sm = new MemoryStream();
            fm.Serialize(sm, SC);
            sm.Seek(0, SeekOrigin.Begin);
            StreamReader reader = new StreamReader(sm);
            string strCart = reader.ReadToEnd();
            reader.Close();            
            HttpCookie hc = new HttpCookie(CookieName);
            hc.Value = Server.UrlEncode(strCart);
            hc.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(hc); 
        }       
    }
    ///// 
    ///// 将ShopCart写入Cookie
    /////     ///// 
ShopCart对象
    ///// 
CookieName,默认为ShopCart
    //public static string ShopCartToCookie(ShopCart SC, string CookieName)
    //{
    //    if (Utils.CheckNull(CookieName)) { CookieName = "ShopCart"; }
    //    if (Utils.CheckNull(SC))
    //    {
    //        Utils.WriteCookie(CookieName, "");
    //        return "";
    //    }
    //    else
    //    {
    //        IFormatter fm = new BinaryFormatter();
    //        Stream sm = new MemoryStream();            
    //        fm.Serialize(sm, SC);
    //        sm.Seek(0, SeekOrigin.Begin);
    //        StreamReader reader = new StreamReader(sm);
    //        string strCart = reader.ReadToEnd();
    //        reader.Close();
    //        Utils.WriteCookie(CookieName, strCart);
    //        return strCart;
    //    }
    //}
    ///// 
    ///// 将Cookie反序列化为ShopCart
    /////     ///// 
CookieName,默认为ShopCart
    //public static ShopCart CookieToShopCart(string CookieName)
    //{
    //    if (Utils.CheckNull(CookieName)) { CookieName = "ShopCart"; }
    //    string StrCart = Utils.GetCookie(CookieName);
    //    if (Utils.CheckNull(StrCart)) 
    //    {
    //        return null;
    //    }
    //    byte[] bt = System.Text.Encoding.Default.GetBytes(StrCart);
    //    Stream sm = new MemoryStream(bt);
    //    IFormatter fm = new BinaryFormatter();
    //    ShopCart SC = (ShopCart)fm.Deserialize(sm);
    //    if (Utils.CheckNull(SC))
    //    {
    //        return null;
    //    }
    //    else
    //    {
    //        return SC;
    //    }
    //}
    protected void btnReadCookie_Click(object sender, EventArgs e)
    {        
        string StrCartNew = Server.UrlDecode(Request.Cookies[CookieName].Value.ToString());
        byte[] bt = System.Text.Encoding.Default.GetBytes(StrCartNew);
        Stream smNew = new MemoryStream(bt);
        IFormatter fmNew = new BinaryFormatter();
        ShopCart SCNew = (ShopCart)fmNew.Deserialize(smNew);
        foreach(ShopCartItem SCI in SCNew.CartItems)
        {
            lblResult.Text += "
产品名称:" + SCI.Name;
        }
    }
}