C#操作Cookie的代碼
namespace Net.String.ConsoleApplication
{
using System;
using System.Web;
public static class CookieHelper
{
/// <summary>
/// 添加cookie
/// </summary>
public static void AddCookie(this HttpContext h,string name, string value)
{
HttpCookie cookieName = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value, System.Text.Encoding.GetEncoding(65001)));
h.Response.Cookies.Add(cookieName);
}
/// <summary>
/// 添加cookie
/// </summary>
public static void AddCookie(this HttpContext h,string name, string value, TimeSpan span)
{
HttpCookie cookieName = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value, System.Text.Encoding.GetEncoding(65001)));
cookieName.Expires = DateTime.Now.Add(span);
h.Response.Cookies.Add(cookieName);
}
/// <summary>
/// 得到cookie
/// </summary>
public static string GetCookie(this HttpContext h, string name)
{
if (h.Request.Cookies[name] != null)
{
if (h.Response.Cookies.Count > 0 && h.Response.Cookies[name] != null)
{
return System.Web.HttpUtility.UrlDecode(h.Response.Cookies[name].Value, System.Text.Encoding.GetEncoding(65001));
}
return System.Web.HttpUtility.UrlDecode(h.Request.Cookies[name].Value, System.Text.Encoding.GetEncoding(65001));
}
else
{ return string.Empty; }
}
/// <summary>
/// 刪除cookie
/// </summary>
public static void RemoveCookie(this HttpContext h,string name)
{
h.Response.Cookies[name].Value = null;
h.Response.Cookies[name].Expires = DateTime.Now.AddDays(-1);
}
/// <summary>
/// 清空cookie
/// </summary>
public static void ClearCookie(this HttpContext h)
{
try
{
foreach (HttpCookie hc in h.Response.Cookies)
{
hc.Value = null;
hc.Expires = DateTime.Now.AddDays(-1);
}
}
catch { }
}
}
}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!