首页 > 代码库 > C#中Cookies的存取

C#中Cookies的存取

<1>

C#中Cookies的存取

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace WebApplication1  
  7. {  
  8.     public class FunCookie  
  9.     {  
  10.         /// <summary>  
  11.         /// 创建Cookie和赋值,及设计Cookie有效天数  
  12.         /// </summary>  
  13.         /// <param name="strCookieName">Cookie名字</param>  
  14.         /// <param name="strCookieValue">Cookie的值</param>  
  15.         /// <param name="intDay">Cookie有效天数</param>  
  16.         /// <returns>布尔值</returns>  
  17.         public static bool SetCookie(string strCookieName,string strCookieValue,int intDay )  
  18.         {  
  19.             try  
  20.             {  
  21.                 HttpCookie cookie = new HttpCookie(strCookieName); //创建一个cookie对象  
  22.                 cookie.Value = strCookieValue; //设置cookie的值  
  23.                 cookie.Expires = DateTime.Now.AddDays(intDay); //或cookie.Expires.AddDays(intDay);设置cookie的有效期  
  24.                 System.Web.HttpContext.Current.Response.Cookies.Add(cookie); //将cookie添加到cookies中  
  25.                 return true;  
  26.             }  
  27.             catch  
  28.             {  
  29.                 return false;  
  30.             }  
  31.         }  
  32.   
  33.         /// <summary>  
  34.         /// 根据Cookie的名字获取Cookie的值  
  35.         /// </summary>  
  36.         /// <param name="strCookieName">要获取的Cookie的名字</param>  
  37.         /// <returns>Cookie的值(string类型)</returns>  
  38.         public static string GetCookie(string strCookieName)  
  39.         {  
  40.             HttpCookie cookie= HttpContext.Current.Request.Cookies[strCookieName];//获取cookie  
  41.             if (cookie != null)  
  42.             {  
  43.                 return cookie.Value; //返回cookie的值  
  44.             }  
  45.             else  
  46.             {  
  47.                 return null;  
  48.             }  
  49.         }  
  50.   
  51.         /// <summary>  
  52.         /// 删除Cookie  
  53.         /// </summary>  
  54.         /// <param name="strCookieName"></param>  
  55.         /// <returns></returns>  
  56.         public static bool DeleteCookie(string strCookieName)  
  57.         {  
  58.             try  
  59.             {  
  60.                 HttpCookie cookie = new HttpCookie(strCookieName);  
  61.                 cookie.Expires = DateTime.Now.AddDays(-1);   
  62.                 HttpContext.Current.Response.Cookies.Add(cookie);  
  63.                 return true;  
  64.             }  
  65.             catch  
  66.             {  
  67.                 return false;  
  68.             }  
  69.         }  
  70.   
  71.           
  72.     }  

C#中Cookies的存取