平时在开发中对于cookie的一些记录笔记
设置cookie的值
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie != null)
{
cookie = new HttpCookie(strName);
cookie.Expires = DateTime.Now.AddDays(-1); //让旧的过期
HttpContext.Current.Response.Cookies.Add(cookie);
}
cookie = new HttpCookie(strName);
cookie.Value = UrlEncode(strValue);
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
获取cookie的值
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
return "";
}
如果你想将一个复杂的数据类型放进一个Cookie,要把这些数据转换成多个字符串,然后将这些字符串同时赋值给Cookie,通过Key的不同来设置也就是键值对的形式
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string key, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie != null)
{
cookie = new HttpCookie(strName);
cookie.Expires = DateTime.Now.AddDays(-1); //让旧的过期
HttpContext.Current.Response.Cookies.Add(cookie);
}
cookie = new HttpCookie(strName);
cookie[key] = UrlEncode(strValue); // 写法2 cookie.Values.Add(key,UrlEncode(strValue));
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
获取cookie的写法为:
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName, string key)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
return "";
}
跨域写cookie
/// <summary>
/// 写Cookie值
/// </summary>
/// <param name="strName">名称KEY</param>
/// <param name="strValue">值</param>
/// <param name="expires">过期时间(分钟)</param>
/// <param name="domain">主机头</param>
public static void WriteCookie(string strName, string strKey, string strValue, int expires, string domain)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie != null)
{
cookie = new HttpCookie(strName);
cookie.Expires = DateTime.Now.AddDays(-1); //让旧的过期
HttpContext.Current.Response.Cookies.Add(cookie);
}
cookie = new HttpCookie(strName);
cookie[strKey] = UrlEncode(strValue);
cookie.Domain = domain;
cookie.Path = "/";
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
另外需要注意的几点是:
1、cookie不能直接修改的,只能通过创建一个新的Cookie发送到浏览器,让浏览器去覆盖旧的Cookie,所以上面的写法都是先创建一个同名的cookie让旧的过期
2、关于cookie的跨域使用 cookie.Domain的域名头默认是当前域名,cookie.Path = “/”; 默认是根目录为作用域