public class CookieHelper
{
public static void AddCookie(object obj, string cookieName)
{
BinaryFormatter bf = new BinaryFormatter(); //声明一个序列化类
MemoryStream ms = new MemoryStream(); //声明一个内存流
bf.Serialize(ms, obj); //执行序列化操作
byte[] result = new byte[ms.Length];
result = ms.ToArray();
string temp = System.Convert.ToBase64String(result);
/*此处为关键步骤,将得到的字节数组按照一定的编码格式转换为字符串,不然当对象包含中文时,进行反序列化操作时会产生编码错误*/
ms.Flush();
ms.Close();
//string temp = XmlUtil.Serializer(obj.GetType(), obj);
HttpCookie cookie = new HttpCookie(cookieName); //声明一个Key为Obj的Cookie对象
cookie.Expires = DateTime.Now.AddDays(1.0); //设置Cookie的有效期到明天为止,此处时间可以根据需要设置
cookie.Value = temp; //将cookie的Value值设置为temp
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
curContext.Response.Cookies.Add(cookie);
}
public static Object ReadCookie(string cookieName)
{
try
{
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
string result = curContext.Request.Cookies[cookieName].Value;
//return (XmlUtil.Deserialize(typeof(UserInfo), result));
byte[] b = System.Convert.FromBase64String(result); //将得到的字符串根据相同的编码格式分成字节数组
MemoryStream ms = new MemoryStream(b, 0, b.Length); //从字节数组中得到内存流
BinaryFormatter bf = new BinaryFormatter();
return bf.Deserialize(ms);
}
catch
{
return null;
}
}
public static void DeleteCookie(string cookieName)
{
try
{
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
//HttpCookie mycookie;
//mycookie = curContext.Request.Cookies[cookieName];
//TimeSpan ts = new TimeSpan(0, 0, 0, 0);//时间跨度
//mycookie.Expires = DateTime.Now.Add(ts);//立即过期
curContext.Response.Cookies.Remove(cookieName);//清除
}
catch
{
}
}
}