/// <summary>
/// Cookies赋值
/// </summary>
/// <param name="strName">主键</param>
/// <param name="strValue">键值</param>
/// <param name="strDay">有效天数,如果不要此参数,cookie在浏览器关闭的时候自动失效</param>
/// <returns></returns>
public static bool SetCookie(string strName, string strValue, int strDay = 0)
{
try
{
HttpCookie Cookie = new HttpCookie(strName);
//Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
if (strDay > 0)
{
Cookie.Expires = DateTime.Now.AddDays(strDay);
}
Cookie.Value = HttpUtility.UrlEncode(strValue);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 读取Cookies
/// </summary>
/// <param name="strName">主键</param>
/// <returns></returns>
public static string GetCookie(string strName)
{
HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strName];
if (Cookie != null)
{
return HttpUtility.UrlDecode(Cookie.Value);
}
else
{
return null;
}
}
/// <summary>
/// 删除Cookies
/// </summary>
/// <param name="strName">主键</param>
/// <returns></returns>
public static bool DelCookie(string strName)
{
try
{
HttpCookie Cookie = new HttpCookie(strName);
//Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
Cookie.Expires = DateTime.Now.AddYears(-10);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
}
示例:
SetCookie("name", "aaa", 1);//赋值,有效期为1天
GetCookie("name");//取值
DelCookie("name");//删除
另外:只要不给cookie设置过期时间,cookie在浏览器关闭的时候自动失效
jQuery操作cookie的插件,大概的使用方法如下
$.cookie('the_cookie'); //读取Cookie值
$.cookie(’the_cookie’, ‘the_value’); //设置cookie的值
$.cookie('the_cookie', 'the_value', { expires: 7 });
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
//新建一个cookie 包括有效期 路径 域名等
$.cookie(’the_cookie’, ‘the_value’, {expires: 7, path: ‘/’, domain: ‘jquery.com’, secure: true});
$.cookie(’the_cookie’, ‘the_value’); //新建cookie
$.cookie(’the_cookie’, null); //删除一个cookie
$.removeCookie('the_cookie');
$.removeCookie('the_cookie', { path: '/' });