【.NET】Cookie操作类

时间:2023-03-08 23:53:50
【.NET】Cookie操作类
 public static class CookiesHelper
{
/// <summary>
/// Cookies赋值
/// </summary>
/// <param name="strName">主键</param>
/// <param name="strValue">键值</param>
/// <param name="strDay">有效天数</param>
/// <returns></returns>
public static bool SetCookie(string strName, string strValue, int strDay)
{
try
{
HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strName];
if (Cookie == null)
{
Cookie = new HttpCookie(strName);
}
Cookie.Expires = DateTime.Now.AddDays(strDay);
Cookie.Value = 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 Cookie.Value.ToString();
}
else
{
return null;
}
} /// <summary>
/// 删除Cookies
/// </summary>
/// <param name="strName">主键</param>
/// <returns></returns>
public static bool DelCookie(string strName)
{
try
{
HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strName];// new HttpCookie(strName);
Cookie.Expires = DateTime.Now.AddDays(-);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
}
}