最近开始学 ASP.NET,然后发现 Cookie 的设置不像 PHP 简单粗暴(PHP Cookie用法),于是就造个轮子省事,注释很详细,这里就不再赘言。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web;r
namespace BuildWheel { /// <summary> /// Cookie辅助类 /// </summary> public class CookieHelper { /// <summary> /// 设置、删除、修改cookie /// </summary> /// <param name="cookieName">cookie名称</param> /// <param name="cookieValue">cookie值</param> /// <param name="expires">过期时间</param> public static void SetCookie(string cookieName, string cookieValue, DateTime expires) { HttpCookie cookie = new HttpCookie(cookieName) { Value = cookieValue, Expires = expires }; HttpContext.Current.Response.Cookies.Add(cookie); }
/// <summary> /// 删除指定cookie /// </summary> /// <param name="cookieName">cookie名称</param> public static void DeleteCookie(string cookieName) { HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName]; if (cookie != null) { cookie.Expires = DateTime.Now.AddYears(-3); HttpContext.Current.Response.Cookies.Add(cookie); } }
/// <summary> /// 清除所有cookie /// </summary> public static void ClearCookies() { HttpContext.Current.Request.Cookies.AllKeys.ToList().ForEach((e) => { HttpCookie cookie = HttpContext.Current.Response.Cookies[e]; cookie.Expires = DateTime.Now.AddYears(-3); HttpContext.Current.Response.Cookies.Add(cookie); }); }
/// <summary> /// 获取cookie值 /// </summary> /// <param name="cookieName">cookie名称</param> /// <returns></returns> public static string GetCookieValue(string cookieName) { HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName]; string cookieValue = string.Empty; if (cookie != null) { cookieValue = cookie.Value; } return cookieValue; } } }
|
有错误欢迎指出~
这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。