【仰天一笑】asp.net c#中對cookie的操作

iDotNetSpace發表於2008-06-16

// 寫cookie
HttpCookie cookie = new HttpCookie("Info");//定義cookie物件以及名為Info的項
DateTime dt = DateTime.Now;//定義時間物件
TimeSpan ts=new TimeSpan(1,0,0,0);//cookie有效作用時間,具體查msdn
cookie.EXPires = dt.Add(ts);//新增作用時間
cookie.Values.Add("user","cxbkkk");//增加屬性
cookie.Values.Add("userid","1203");
Response.AppendCookie(cookie);//確定寫入cookie中        讀取cookie
if(Request.Cookies["Info"]!=null)
{
     string temp=Convert.ToString(Request.Cookies["Info"].Values["user"])+"  "+Convert.ToString(Request.Cookies["Info"].Values["userid"]);
    //讀全部就用Request.Cookies["Info"].Value)
     if(temp=="")
     {
         Response.Write("空");
     }
     else
        Response.Write(temp);
}
else
{
    Response.Write("error");
}        修改cookie
Response.Cookies["Info"]["user"] = "2";
Response.Cookies["Info"].Expires = DateTime.Now.AddDays(1);      

// 刪除cookie下的屬性
HttpCookie acookie=Request.Cookies["Info"];
acookie.Values.Remove("userid");
acookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(acookie);        刪除所有cookie,就是設定過期時間為現在就行了
int limit=Request.Cookies.Count - 1;
for(int i=0;i{
   acookie = Request.Cookies(i)
   acookie.Expires = DateTime.Now.AddDays(-1)
   Response.Cookies.Add(acookie)
}


// 讀取所有 cookies
HttpCookieCollection cookies;
HttpCookie oneCookie;
cookies = Request.Cookies;

string[] cookieArray = cookies.AllKeys;
for (int i=0; i < cookieArray.Length; i++)
{
 oneCookie = cookies[cookieArray[i]];
 Response.Write(oneCookie.Name + " - " + oneCookie.Value);
}

// 新增單個cookies
if (Request.Browser.Cookies == true)
{
 if (Request.Cookies["LastVisited1"] == null)
 {
  HttpCookie newCookie = new HttpCookie("LastVisited1",DateTime.Now.ToString());
  newCookie.Expires = DateTime.Now.AddYears(1);
  Response.Cookies.Add(newCookie);
 }
 else
 {
  Response.Write(Request.Cookies["LastVisited1"].Value);
 } 
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-349327/,如需轉載,請註明出處,否則將追究法律責任。

相關文章