About the operation of cookies in asp.net c#
Author:Eve Cole
Update Time:2009-06-30 15:58:37
I wrote down how to operate cookies when I had some free time today. Although it is very simple, I don’t want to forget it later. I had forgotten it before and had to experiment a lot before figuring it out. It was frustrating.
The following is to write cookies
1 HttpCookie cookie = new HttpCookie("Info");//Define the cookie object and the item named Info
2 DateTime dt = DateTime.Now;//Define time object
3 TimeSpan ts=new TimeSpan(1,0,0,0);//Cookie effective time, check msdn for details
4 cookie.Expires = dt.Add(ts);//Add action time
5 cookie.Values.Add("user","cxbkkk");//Add attributes
6 cookie.Values.Add("userid","1203");
7 Response.AppendCookie(cookie);//Confirm to write to the cookie and read the cookie
1 if(Request.Cookies["Info"]!=null)
2 {
3 string temp=Convert.ToString(Request.Cookies["Info"].Values["user"])+" "+Convert.ToString(Request.Cookies["Info"].Values["userid"]);
4 //To read all, use Request.Cookies["Info"].Value)
5 if(temp=="")
6 {
7 Response.Write("empty");
8}
9 else
10 Response.Write(temp);
11 }
12 else
13 {
14 Response.Write("error");
15 } Modify cookies
1 Response.Cookies["Info"]["user"] = "2";
2 Response.Cookies["Info"].Expires = DateTime.Now.AddDays(1); Delete attributes under cookie
1 HttpCookie acookie=Request.Cookies["Info"];
2 acookie.Values.Remove("userid");
3 acookie.Expires = DateTime.Now.AddDays(1);
4 Response.Cookies.Add(acookie); To delete all cookies, just set the expiration time to now.
1 int limit=Request.Cookies.Count - 1;
2 for(int i=0;i<limit;i++)
3 {
4 acookie = Request.Cookies(i)
5 acookie.Expires = DateTime.Now.AddDays(-1)
6 Response.Cookies.Add(acookie)
7 } Now you don’t have to look around