1 cookie 使用
写入cookie
HttpCookie cookie = new HttpCookie("MyCookieName", "string value"); Response.Cookies.Add(cookie);
读取 cookie
HttpCookie cookie = Request.Cookies["MyCookieName"]; if( cookie != null ) labCookie1.Text = cookie.Value; else labCookie1.Text = "未定义";
删除
HttpCookie cookie = new HttpCookie("MyCookieName", null); cookie.Expires = new DateTime(1900, 1, 1); Response.Cookies.Add(cookie);
保存对象
一般方法1:
public class DisplaySettings { public int Style; public int Size; public override string ToString() { return string.Format("Style = {0}, Size = {1}", this.Style, this.Size); } }
private void WriteCookie_2a() { DisplaySettings setting = new DisplaySettings { Style = 1, Size = 24 }; HttpCookie cookie = new HttpCookie("DisplaySettings1"); cookie["Style"] = setting.Style.ToString(); cookie["Size"] = setting.Size.ToString(); Response.Cookies.Add(cookie); } private void ReadCookie_2a() { HttpCookie cookie = Request.Cookies["DisplaySettings1"]; if( cookie == null ) labDisplaySettings1.Text = "未定义"; else { DisplaySettings setting = new DisplaySettings(); setting.Style = cookie["Style"].TryToInt(); setting.Size = cookie["Size"].TryToInt(); labDisplaySettings1.Text = setting.ToString(); } }
2 json方法
private void WriteCookie_2b() { DisplaySettings setting = new DisplaySettings { Style = 2, Size = 48 }; HttpCookie cookie = new HttpCookie("DisplaySettings2", setting.ToJson()); Response.Cookies.Add(cookie); } private void ReadCookie_2b() { HttpCookie cookie = Request.Cookies["DisplaySettings2"]; if( cookie == null ) labDisplaySettings2.Text = "未定义"; else { DisplaySettings setting = cookie.Value.FromJson<DisplaySettings>(); labDisplaySettings2.Text = setting.ToString(); } }
/// <summary> /// 将一个对象序列化成 JSON 格式字符串 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string ToJson(this object obj) { if( obj == null ) return string.Empty; JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Serialize(obj); } /// <summary> /// 从JSON字符串中反序列化对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cookie"></param> /// <returns></returns> public static T FromJson<T>(this string cookie) { if( string.IsNullOrEmpty(cookie) ) return default(T); JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Deserialize<T>(cookie); }
以上转载自:fish li