-----------------------------------------------------------------------------------------------------------
C#中Cookie的存取
-----------------------------------------------------------------------------------------------------------
/// <summary>
/// 創建cookie並賦值,設置cookie有效時間
/// </summary>
/// <param name="strCookieName">cookie名字</param>
/// <param name="strCookieValue">cookie值</param>
/// <param name="intDay">cookie有效天數</param>
/// <returns>布爾值</returns>
public static bool SetCookie(string strCookieName, string strCookieValue, int intDay)
{
try
{
//創建一個cookie對象
HttpCookie cookie = new HttpCookie(strCookieName);
//設置cookie的值
cookie.Value = strCookieValue;
//設置cookie的有效期 或者cookie.Expires.AddDays(intDay);
cookie.Expires = DateTime.Now.AddDays(intDay);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 根據cookie的名字獲取cookie值
/// </summary>
/// <param name="strCookieName">要獲取的cookie名</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strCookieName)
{
//獲取cookie
HttpCookie cookie = HttpContext.Current.Request.Cookies[strCookieName];
if (cookie!=null)
{
return cookie.Value;
}
else
{
return null;
}
}
/// <summary>
/// 根據cookie名稱,刪除cookie
/// </summary>
/// <param name="strCookieName">cookie名</param>
/// <returns>布爾值 true 刪除成功 false 刪除失敗</returns>
public static bool DeleteCookie(string strCookieName)
{
try
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strCookieName];
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
-----------------------------------------------------------------------------------------------------------
jQuery中Cookie的存取
-----------------------------------------------------------------------------------------------------------
//創建一個key為uName,值為cookievalue的cookie,有效期為3天
$.cookie("uName", "cookievalue", { expires: 3});
//讀取cookie值
$.cookie("uName");
//刪除cookie
$.cookie("uName", null);
注意:要記得引用兩個js文件
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<script src="jquery.cookie-v1.4.1.js" type="text/javascript"></script>
