c#.net在WEB頁中設定COOKIES

來源:互聯網
上載者:User

一、設定cookies的方法很簡單,有以下兩種方法: 

1、直接添加Cookie值: 
   Response.Cookies["userName"] = "Tom";  
   Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1) ; \\有效期間1天,到期時間,在Cookies檔案中無法查看,也不能調用. 
   Response.Cookies["userName"].Expires = DateTime.Now.AddYears(-1) ; \\設定cookie到期

2、建立Cookie對象的一個執行個體: 
   HttpCookie cookie=new HttpCookie("userName"); 
   cookie.Value = "Tom"; 
   cookie.Expires = DateTime.Now.AddDays(1) ;  
   Response.Cookies.Add(aCookie)  

用以上任一方法都可以產生一個有“userName”項的檔案, 在你的Internet臨時檔案夾中你可以查看它。 

也可以建立和添加有子鍵的Cookies,如: 
Response.Cookies["userInfo"]["userName"] = "Tom";  

或: 
   HttpCookie cookie=new HttpCookie("userInfo"); 
   cookie.Values["userName"] = "Tom"; 
   aCookie.Expires = DateTime.Now.AddDays(1);  
   Response.Cookies.Add(aCookie)  

二、檢索Cookies: 
  Cookies某一鍵的值為:  
  Server.HtmlEncode(Request.Cookies["userInfo"]["userName"]) 
  你可以用Response.Write()方法輸出它到頁面,如: 
  Response.Write(Server.HtmlEncode(Request.Cookies["userInfo"]["userName"])); 

  或賦值給其它變數: 

  string strCookie1=Server.HtmlEncode(Request.Cookies["userInfo"]["userName"]); 
   
  用Cookies[i]數組可以檢索所有項和子鍵,如: 
  string[] cooName  = new string[Request.Cookies.Count]; 
  string[] cooValue = new string[Request.Cookies.Count];   
  HttpCookie aCookie; 
  for(int i=0;i<Request.Cookies.Count;i++){ 
    aCookie = Request.Cookies[i];  
    cooName[i]  = Server.HtmlEncode(aCookie.Name); 
    if(!aCookie.HasKeys){ 
       cooValue[i] = Server.HtmlEncode(aCookie.Value); 
    }else{ 
      string[] subcooName  = new string[aCookie.Values.Count]; 
      string[] subcooValue = new string[aCookie.Values.Count];  
      for(int j=0;j<aCookie.Values.Count;j++){   
        subcooName[j]  = Server.HtmlEncode(aCookie.Values.AllKeys[j]); 
        subcooValue[j] = Server.HtmlEncode(aCookie.Values[j]); 
      } 
    } 
  } 

三、修改Cookies 
   如果是數實值型別的Cookie值,比如訪問次數,你可以讀取該值進行加減操作後再存回,一般的修改直接存入新值就可以了,系統自動用新值覆蓋原值,存入的方法與建立相同。 

四、刪除Cookies 
刪除Cookies只要把有效期間設為失效就可以了,如在建立時設有效期間為一天: 
  cookie.Expires = DateTime.Now.AddDays(1) ; 
要刪除則設為: 
cookie.Expires = DateTime.Now.AddDays(-1) ; 

  刪除子鍵: 
HttpCookie cookie; 
cookie = Request.Cookies["userInfo"]; 
  aCookie.Values.Remove("userName"); 
  aCookie.Expires = DateTime.Now.AddDays(1); 
  Response.Cookies.Add(aCookie);  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.