最近开始学ASP.NET,然后发现cookie的设置不像php简单粗暴(php cookie用法),于是就造个轮子省事,注释很详细,这里就不再赘言。 using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Web;namespace BuildWheel{ /// /// Cookie辅助类 /// public class CookieHelper { /// /// 设置、删除、修改cookie /// /// cookie名称 /// cookie值 /// 过期时间 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); } /// /// 删除指定cookie /// /// cookie名称 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); } } /// /// 清除所有cookie /// 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); }); } /// /// 获取cookie值 /// /// cookie名称 /// 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; } }} 有错误欢迎指出~ 本文链接: ,尊重共享,欢迎转载! |
|