首页 > 代码库 > .Net mvc cookie 操作封装方法
.Net mvc cookie 操作封装方法
对cookie操作不太熟悉的可以参考一下。
一般来说 cookie是个针对访问者电脑存储数据的东西,可以把一个cookie看作一个表,有表名,可以有很多行,每一行有两个字段,key和value,key唯一,可以通过key找到对应的值 value.
封装方法:
#region 设置cookie /// <summary> /// 设置cookie /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="cookiename">cookie名称</param> /// <param name="cookiedays">cookie保留多少天(默认3天),可以用小数表示</param> public static void SetCookies(HttpResponseBase Response, HttpRequestBase Request, string key, string value, string cookiename,double cookiedays=3) { HttpCookie cookie = Request.Cookies[cookiename]; //cookie.ExpirationSet = false; if (cookie == null) { cookie = new HttpCookie(cookiename); cookie.Values.Add(key, value); } else { if (cookie.Values[key] != null) { cookie[key] = value; } else cookie.Values.Add(key, value); } if (HttpContext.Current != null) { if (HttpContext.Current.Request.Url.DnsSafeHost.Contains("kinpan.com")) { cookie.Domain = "kinpan.com"; } } //cookie.Domain = ConfigurationManager.AppSettings["kinpandomain"]; cookie.Path = "/"; cookie.Expires = DateTime.Now.AddDays(cookiedays); Response.Cookies.Remove(cookiename); Response.Cookies.Add(cookie); } #endregion #region 删除cookie /// <summary> /// 删除cookie,我们没有直接删除的权限,但是新建一个同名cookie,设置为过期,那么浏览器会去检测和删除同名的cookie。 /// </summary> /// <param name="cookiename">cookie名称</param> public static void deleteCookie(HttpResponseBase Response,string cookiename) { if (cookiename.HasValue()) { HttpCookie aCookie = new HttpCookie(cookiename); aCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(aCookie); } } #endregion #region 获取整个cookie /// <summary> /// 获取整个cookie /// </summary> /// <param name="cookiename"></param> /// <returns></returns> public static HttpCookie GetCookie(HttpRequestBase Request, string cookiename) { return HttpContext.Current.Request.Cookies[cookiename]; } #endregion #region 获取cookie里的键对应的值 /// <summary> /// 获取cookie里的键对应的值 /// </summary> /// <param name="name">名称</param> /// <param name="key">键</param> /// <returns>返回键对应的值</returns> public static string GetCookies(HttpRequestBase Request, string name, string key) { if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(key)) { return String.Empty; } else { HttpCookie cookie = Request.Cookies[name]; if (cookie != null && cookie[key] != null) { string value = http://www.mamicode.com/cookie[key].ToString();>.Net mvc cookie 操作封装方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。