using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Cookie : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //创建Cookie protected void Button1_Click(object sender, EventArgs e) { HttpCookie Cookie = new HttpCookie("MyCookie"); DateTime dt=DateTime.Now; TimeSpan ts=new TimeSpan (0,0,1,0,0);//过期时间设置为1分钟 //设置过期时间 Cookie.Expires = dt.Add(ts); Cookie.Values.Add("name","yys"); Cookie.Values.Add("age","24"); Response.AppendCookie(Cookie); } //读取 protected void Button2_Click(object sender, EventArgs e) { if(Request.Cookies["Mycookie"]!=null) { Response.Write(Request.Cookies["Mycookie"].Value); } } //修改 protected void Button3_Click(object sender, EventArgs e) { //获取客户端的Cookie对象 HttpCookie cok = Request.Cookies["MyCookie"]; if(cok!=null) { cok.Values["name"] = "Abner"; cok.Values.Set("age","20"); //往Cookie里加入新的内容 cok.Values.Set("sex","男"); Response.AppendCookie(cok); Response.Write(Request.Cookies["MyCookie"].Value); } } //删除 protected void Button4_Click(object sender, EventArgs e) { HttpCookie co=Request.Cookies["MyCookie"]; co.Values.Remove("sex");//删除键为“sex”的键值对 Response.Write(Request.Cookies["MyCookie"].Value); TimeSpan ts = new TimeSpan(-1,0,0,0); co.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在 } }