1、增加Cookie的写入方法:
/// <summary>
/// 写 Cookies
/// </summary>
/// <param name="cookieName">主键</param>
/// <param name="cookieValue">键值</param>
/// <param name="hours">有效时间(小时)</param>
/// <returns></returns>
public static bool SetCookie(string cookieName, string cookieValue, int hours)
{
try
{
HttpCookie Cookie = new HttpCookie(cookieName);
if (!string.IsNullOrEmpty(Settings.Domain))
Cookie.Domain = Settings.Domain;
Cookie.Expires = DateTime.Now.AddHours(hours);
Cookie.Value = SecurityHelper.Encrypt(cookieValue);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
}
2、增加Cookie的读取方法:
/// <summary>
/// 读取Cookies
/// </summary>
/// <param name="CookieName">主键</param>
/// <returns></returns>
public static string GetCookie(string CookieName)
{
HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[CookieName];
if (Cookie != null)
{
return SecurityHelper.Decrypt(Cookie.Value.ToString());
}
else
{
return null;
}
}
3、增加对Cookie的删除方法:
/// <summary>
/// 删除Cookies
/// </summary>
/// <param name="cookieName">主键</param>
/// <returns></returns>
public static bool DeleteCookie(string cookieName)
{
try
{
HttpCookie Cookie = new HttpCookie(cookieName);
if (!string.IsNullOrEmpty(Settings.Domain))
{
Cookie.Domain = Settings.Domain;
}
Cookie.Expires = DateTime.Now.AddDays(-1);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
}
4、增加Cookie的过期时间设置:
/// <summary>
/// 更新cookie过期时间
/// </summary
/// <param name="cookieName"></param>
/// <param name="cookieValue"></param>
/// <param name="minutes"></param>
public static void ModCookies(string cookieName, string cookieValue, int minutes)
{
var httpCookie = HttpContext.Current.Response.Cookies[cookieName];
if (httpCookie != null)
{
httpCookie.Value = cookieValue;
httpCookie.Expires = DateTime.Now.AddMinutes(minutes);
}
}