[C#] cookie的常見操作

Designed by Freepik
此篇為筆記備忘
轉載自https://www.cnblogs.com/sntetwt/p/4825270.html
圖片來源Designed by Freepik


  1. 寫入Cookie

HttpCookie cookie = new HttpCookie("MyCook");//初始化並設置Cookie的名稱
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(0, 0, 1, 0, 0);//過期時間為1分鐘
cookie.Expires = dt.Add(ts);//設置過期時間
cookie.Values.Add("userid", "userid_value");
cookie.Values.Add("userid2", "userid2_value2");
Response.AppendCookie(cookie);

//輸出該Cookie的所有內容
//Response.Write(cookie.Value);
//輸出為:userid=userid_value&userid2=us erid2_value2

  1. 讀取Cookie

//HttpCookie cok = Request.Cookies["MyCook"];

if (Request.Cookies["MyCook"] != null)
{
 Response.Write("Cookie中鍵值為userid的值:" + Request.Cookies["MyCook"]["userid"]);

 Response.Write("Cookie中鍵值為userid2的值" + Request.Cookies["MyCook"]["userid2"]);

 Response.Write(Request.Cookies["MyCook"].Value); //輸出全部的值
}

  1. 修改Cookie

//獲取客戶端的Cookie對象
HttpCookie cok = Request.Cookies["MyCook"];

if (cok != null)
{
 cok.Expires = DateTime.Now.AddHours(2);

 //修改Cookie的兩種方法
 cok.Values["userid"] = "alter-value";
 cok.Values.Set("userid", "alter-value");

 //往Cookie裡加入新的內容
 cok.Values.Set("newid", "newValue");
 Response.AppendCookie(cok);
}

  1. 刪除Cookie

HttpCookie cok = Request.Cookies["MyCook"];
if (cok != null)
{
 if (!true) //CheckBox1.Checked
 {
  cok.Values.Remove("userid"); //移除鍵值為userid的值
 }
 else
 {
  TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
  cok.Expires = DateTime.Now.Add(ts);
//刪除整個Cookie,只要把過期時間設置為現在
 }
 Response.AppendCookie(cok);
}

**********************************************
  1. 其他處理方式

HttpCookie addCookie = new HttpCookie("mycookie");
//添加cookie的key值
addCookie.Values.Add("name", "hsj");

var cookie = Request.Cookies["mycookie"];
if (cookie != null && cookie.HasKeys)
{
 //獲取cookie中key的兩種方法
 var name1 = cookie["name"];
 var name2 = cookie.Values["name"];
 if (name1 != "hsj")
 {
  //設置cookie中key的兩種方法
  cookie.Values["name"] = "zhangsan";
  cookie.Values.Set("name", "lishi");
 }
}
//更新cookie中現有的值
Response.SetCookie(cookie);
//將cookie添加到http respose中
Response.AppendCookie(addCookie);

沒有留言:

張貼留言

技術提供:Blogger.