清除Cookie的数据
清除Cookie的数据
1.清除已知。key为你所知cookie的名字。
//清除cookies foreach (string key in cookies) { contenxt.Response.Cookies[key].Expires = DateTime.Now.AddDays(-1); }
2.清除所有Cookie。
for (int i = 0; i < this.Request.Cookies.Count; i++) { this.Response.Cookies[this.Request.Cookies[i].Name].Expires = DateTime.Now.AddDays(-1); }
为了更好的使用我们可以把这二个方法封装。
/// <summary> /// 清除指定cookie /// </summary> /// <param name="contenxt">The contenxt.</param> /// <param name="cookies">The cookies.</param> public static void ClearCookies(HttpContext contenxt,params string[] cookies) { //清除cookies foreach (string key in cookies) { contenxt.Response.Cookies[key].Expires = DateTime.Now.AddDays(-1); } } /// <summary> /// 清空所有cookie /// </summary> /// <param name="contenxt">The contenxt.</param> public static void ClearCookiesAll(HttpContext contenxt) { //清除cookies for (int i = 0; i < contenxt.Request.Cookies.Count; i++) { contenxt.Response.Cookies[contenxt.Request.Cookies[i].Name].Expires = DateTime.Now.AddDays(-1); } }