码迷,mamicode.com
首页 > Windows程序 > 详细

C# Cookie方法

时间:2017-09-05 13:28:51      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:else   bsp   button   客户端   ted   ons   date   res   cli   

 1 //写入
 2   protected void Button1_Click(object sender, EventArgs e)
 3   {
 4     HttpCookie cookie=new HttpCookie("MyCook");//初使化并设置Cookie的名称
 5     DateTime dt=DateTime.Now;
 6     TimeSpan ts = new TimeSpan(0, 0, 1,0,0);//过期时间为1分钟
 7     cookie.Expires = dt.Add(ts);//设置过期时间
 8     cookie.Values.Add("userid", "userid_value");
 9     cookie.Values.Add("userid2","userid2_value2");
10     Response.AppendCookie(cookie);
11     //输出该Cookie的所有内容
12     //Response.Write(cookie.Value);//输出为:userid=userid_value&userid2=userid2_value2 
13   }
14 
15   //读取
16   protected void Button2_Click(object sender, EventArgs e)
17   {
18 
19     // HttpCookie cokie = new HttpCookie("MyCook");//初使化
20     if (Request.Cookies["MyCook"]!=null)
21     {
22       //Response.Write("Cookie中键值为userid的值:" + Request.Cookies["MyCook"]["userid"]);//整行
23       //Response.Write("Cookie中键值为userid2的值" + Request.Cookies["MyCook"]["userid2"]);
24       Response.Write(Request.Cookies["MyCook"].Value);//输出全部的值
25     }
26   }
27 
28   //修改Cookie
29   protected void Button3_Click(object sender, EventArgs e)
30   {
31     //获取客户端的Cookie对象
32     HttpCookie cok = Request.Cookies["MyCook"];
33         
34     if (cok != null)
35     {
36       //修改Cookie的两种方法
37       cok.Values["userid"] = "alter-value";
38       cok.Values.Set("userid", "alter-value");
39 
40       //往Cookie里加入新的内容
41       cok.Values.Set("newid", "newValue");
42       Response.AppendCookie(cok);
43     }      
44   }
45 
46   //删除Cookie
47   protected void Button4_Click(object sender, EventArgs e)
48   {
49 
50     HttpCookie cok = Request.Cookies["MyCook"];
51     if (cok != null)
52     {
53       if (!CheckBox1.Checked)
54       {
55         cok.Values.Remove("userid");//移除键值为userid的值
56       }
57       else
58       {
59         TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
60         cok.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在
61       }
62       Response.AppendCookie(cok);
63     }
64   }

 

C# Cookie方法

标签:else   bsp   button   客户端   ted   ons   date   res   cli   

原文地址:http://www.cnblogs.com/fz1024055448/p/7478082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!