网上找到的一个购物车类,但是经过反复的测试,发现其中序列化后数据会出现问题,改成以下的模块就正常了。
代码
/// <summary>
/// 将ShoppingCart写入Cookie
/// </summary>
/// <param name="SC">ShoppingCart对象</param>
/// <param name="CookieName">CookieName,默认为ShoppingCart</param>
public static string ShopCartToCookie(ShoppingCart SC, string CookieName)
{
if (CookieName == null || CookieName=="") { CookieName = "ShoppingCart"; }
if (SC == null)
{
WriteCookie(CookieName, "",148);
return "";
}
else
{
IFormatter fm = new BinaryFormatter();
MemoryStream sm = new MemoryStream();
fm.Serialize(sm, SC);
byte[] bty = new byte[sm.Length];
bty = sm.ToArray();
string strCart = Convert.ToBase64String(bty);
strCart = System.Web.HttpContext.Current.Server.UrlEncode(strCart);
WriteCookie(CookieName, strCart,148);
return strCart;
}
}
/// <summary>
/// 将Cookie反序列化为ShopCart
/// </summary>
/// <param name="CookieName">CookieName,默认为ShopCart</param>
public static ShoppingCart CookieToShopCart(string CookieName)
{
if (CookieName == null || CookieName=="") { CookieName = "ShoppingCart"; }
string StrCart = System.Web.HttpContext.Current.Server.UrlDecode(GetCookie(CookieName));
if (StrCart==null||StrCart=="")
{
return null;
}
byte[] bt = Convert.FromBase64String(StrCart);
Stream sm = new MemoryStream(bt);
IFormatter fm = new BinaryFormatter();
ShoppingCart SC = (ShoppingCart)fm.Deserialize(sm);
if (SC==null)
{
return null;
}
else
{
return SC;
}
}
/// 将ShoppingCart写入Cookie
/// </summary>
/// <param name="SC">ShoppingCart对象</param>
/// <param name="CookieName">CookieName,默认为ShoppingCart</param>
public static string ShopCartToCookie(ShoppingCart SC, string CookieName)
{
if (CookieName == null || CookieName=="") { CookieName = "ShoppingCart"; }
if (SC == null)
{
WriteCookie(CookieName, "",148);
return "";
}
else
{
IFormatter fm = new BinaryFormatter();
MemoryStream sm = new MemoryStream();
fm.Serialize(sm, SC);
byte[] bty = new byte[sm.Length];
bty = sm.ToArray();
string strCart = Convert.ToBase64String(bty);
strCart = System.Web.HttpContext.Current.Server.UrlEncode(strCart);
WriteCookie(CookieName, strCart,148);
return strCart;
}
}
/// <summary>
/// 将Cookie反序列化为ShopCart
/// </summary>
/// <param name="CookieName">CookieName,默认为ShopCart</param>
public static ShoppingCart CookieToShopCart(string CookieName)
{
if (CookieName == null || CookieName=="") { CookieName = "ShoppingCart"; }
string StrCart = System.Web.HttpContext.Current.Server.UrlDecode(GetCookie(CookieName));
if (StrCart==null||StrCart=="")
{
return null;
}
byte[] bt = Convert.FromBase64String(StrCart);
Stream sm = new MemoryStream(bt);
IFormatter fm = new BinaryFormatter();
ShoppingCart SC = (ShoppingCart)fm.Deserialize(sm);
if (SC==null)
{
return null;
}
else
{
return SC;
}
}