C#操作cookie的例子(读取、删除、写入)
本文导语: 代码如下,具体实现看注释。 代码示例: #region Cookie处理 /// /// 写cookie值 /// /// 名称 /// 值 public static void WriteCookie(string strName, string strValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName...
代码如下,具体实现看注释。
#region Cookie处理
///
/// 写cookie值
///
/// 名称
/// 值
public static void WriteCookie(string strName, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
///
/// 写cookie值
/// www.
/// 名称
/// 索引
/// 值
public static void WriteCookie(string strName, string key, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie[key] = strValue;
HttpContext.Current.Response.AppendCookie(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.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
///
/// 写cookie值
///
/// 名称
/// 值
/// 过期时间(分钟)
/// cookie存在的域范围
public static void WriteCookie(string strName, string strValue, int expires, string domain)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
cookie.Domain = domain;
HttpContext.Current.Response.AppendCookie(cookie);
}
///
/// 读cookie值
///
/// 名称
/// cookie值
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
///
/// 读cookie值
///
/// 名称
/// cookie值
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 HttpContext.Current.Request.Cookies[strName][key].ToString();
}
return "";
}
///
/// 删除Cookies
///
/// 名称
/// 域名
///
public static void DelCookie(string strName, string domain)
{
HttpCookie cookie = new HttpCookie(strName);
WriteCookie(strName, "", -60, domain);
}
///
/// 删除Cookies
///
/// 名称
///
public static void DelCookie(string strName)
{
HttpCookie cookie = new HttpCookie(strName);
WriteCookie(strName, "", -60);
}
#endregion