首页 > 代码库 > .net Cookie的操作
.net Cookie的操作
using System; using System.Collections.Generic; using System.Web; namespace Zhong.Core { /// <summary> /// Cookie操作类 /// </summary> public class CookieHelper { private static readonly string CookieName = "Zhong"; /// <summary> /// 设置Cookie /// </summary> /// <param name="name">名称</param> /// <param name="values">键/值对</param> /// <param name="expires">过期超时时间(秒),为0时不设置过期时间</param> /// <param name="domain">域名</param> /// <param name="path">路径</param> public static void SetCookie(string name, Dictionary<string, string> values, int expires, string domain = null, string path = null) { HttpCookie cookie = HttpContext.Current.Response.Cookies[name]; if (cookie == null) { cookie = new HttpCookie(name); } foreach (KeyValuePair<string, string> kv in values) { cookie.Values.Add(kv.Key, kv.Value); } if (domain != null) { cookie.Domain = domain; } if (path != null) { cookie.Path = path; } if (expires != 0) { cookie.Expires = DateTime.Now.AddSeconds(expires); //过期时间 } HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// 设置Cookie /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void SetCookie(string key, string value) { SetCookie(CookieName, new Dictionary<string, string> { { key, value } }, 0); } /// <summary> /// 根据名称与键读取Cookie /// </summary> /// <param name="name">名称</param> /// <param name="key">键</param> /// <returns></returns> public static string GetCookie(string name, string key) { string returnVal = null; HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; if (cookie != null) { returnVal = cookie[key]; } return returnVal; } /// <summary> /// 根据键读取Cookie /// </summary> /// <param name="key">键</param> /// <returns></returns> public static string GetCookie(string key) { return GetCookie(CookieName, key); } /// <summary> /// 根据名称获取Cookie /// </summary> /// <param name="name">名称</param> /// <returns></returns> public static string GetCookieByName(string name) { string returnVal = null; HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; if (cookie!= null) { returnVal = cookie.Value; } return returnVal; } /// <summary> /// 删除Cookie /// </summary> /// <param name="name">名称</param> public static void DeleteCookie(string name) { HttpCookie cookie = HttpContext.Current.Response.Cookies[name]; if (cookie != null) { cookie.Expires = DateTime.Now.AddYears(-1); cookie.Values.Clear(); } HttpContext.Current.Response.Cookies.Add(cookie); } } }
.net Cookie的操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。