C# CookieHelper

1.写cookie值

/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
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);
}

2. 读cookie值

/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
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 "";
}

3.删除cookie对象

/// <summary>
/// 删除cookie对象
/// </summary>
/// <param name="cookieName"></param>
public static void RemoveCookie(string cookieName)
{
HttpCookie objCookie = new HttpCookie(cookieName);
objCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(objCookie);
}

原文地址:https://www.cnblogs.com/xiao-wo-niu/p/12882825.html