Cookie
近日饿习管理状态中,浅尝阶段。革命在继续,更新repeat中!!
//写入Cookie
protected void Button1_Click(object sender, EventArgs e) { HttpCookie cok = new HttpCookie("CaseInfo");//定创建名为CaseInfo的cookies子集cok; cok.Values.Add("key1", "小虾");//给一个cookie添加多个键/值对; cok.Values.Add("key2", "大虾");//等同于: cok[“key2”]=”大虾“; cok.Expires = Now.AddDays(2);//设置作用时间 Response.AppendCookie(cok); } ①取出cok对象的值: HttpCookie cok = Request.Cookies["CaseInfo"]; string cookieValue = cok.Value; ②取出键对应的值: HttpCookie cok = Request.Cookies["CaseInfo"]; string val1 = cookies.Values["key1"]; string val2 = cookies.Values["key2"]; ③关于将该Cookie添加到Cookies集合中: —— Response.Cookies.Add(cok)方法: —— Response.AppendCookie(cok)方法: 听说没什么大的区别(°Д°),不过听说add()有更多的重载方法: 如Cookies.Add(strPath, strName, strValue, [bPersist])
//删除cookie其中一个属性(键值对):<cookieVar>.Values.Remove()
protected void Button2_Click(object sender, EventArgs e) { HttpCookie cok = Request.Cookies["CaseInfo"]; if (cok != null) { cok.Values.Remove("key1"); Response.AppendCookie(cok); } }
跑题小Tips: 事件的修饰符都用protected(当然public也行,但不安全),主要原因是aspx页面(inherit=JuSNS.Web.Default)是继承aspx.cs页面(public partial class Default)的。设置为protected修饰符,才能在子类中访问父类。
//删除整个Cookie(设置过期时间):<cookieVar>.Expires=DateTime.Now.AddDay(-1);
protected void Button3_Click(object sender, EventArgs e) { HttpCookie cok = Request.Cookies["CaseInfo"]; cok.Expires = DateTime.Now.AddDays(-1); Response.AppendCookie(cok); }
//读取Cookie
protected void Button5_Click(object sender, EventArgs e) { if (Request.Cookies["CaseInfo"] != null) { string temp = Convert.ToString(Request.Cookies["CaseInfo"].Values["key1"]) + " " + Convert.ToString(Request.Cookies["CaseInfo"].Values["key2"]);//原来Convert.ToString()的参数还可以这么搞! if (!string.IsNullOrEmpty(temp)) { Response.Write(temp); } else { Response.Write("字符串为空"); } } else { Response.Write("为空"); } }
获取一个cookie对象的某键对应的值: Request.Cookies["CaseInfo"].Values("key1");
用一个string类型的对象temp储存该值,通过判断temp
string.IsNullOrEmpty()方法用于判断字符串是否为"空字符串或无值"。