public class CookieHelper
{
/// <summary>
/// 1.1添加Cookie
/// </summary>
/// <param name="ckname"></param>
/// <param name="ckvalue"></param>
public static void AddCookie(string ckname, string ckvalue)
{
AddCookie(ckname, ckvalue, DateTime.Now.AddDays(1.0));
}
/// <summary>
/// 1.2添加一个Cookie
/// </summary>
/// <param name="ckname">cookie名</param>
/// <param name="ckvalue">cookie值</param>
/// <param name="expires">过期时间 DateTime</param>
public static void AddCookie(string ckname, string ckvalue, DateTime expires)
{
HttpCookie cookie = new HttpCookie(ckname)
{
Value = ckvalue,
Expires = expires
};
HttpContext.Current.Response.Cookies.Add(cookie);
}
/// <summary>
/// 2读取cookie
/// </summary>
/// <param name="ckname">ckname</param>
/// <returns></returns>
public static string ReadCookie(string ckname)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[ckname];
string str = string.Empty;
if (cookie != null)
{
str = cookie.Value;
}
return str;
}
/// <summary>
/// 3修改cookie
/// </summary>
/// <param name="ckname"></param>
/// <param name="ckvalue"></param>
public static void EditCookie(string ckname, string ckvalue)
{
if (HttpContext.Current.Request.Cookies[ckname] == null)
{
AddCookie(ckname, ckvalue, DateTime.Now.AddDays(1.0));
}
else
{
HttpContext.Current.Response.Cookies[ckname].Value = ckvalue;
HttpContext.Current.Response.Cookies[ckname].Expires = DateTime.Now.AddDays(1);
}
}
/// <summary>
/// 4删除cookie
/// </summary>
/// <param name="ckname">ckname</param>
public static void ClearCookie(string ckname)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[ckname];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddYears(-3);
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
}