-----------------------------------------------------------------------------------------------------------
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>