我使用以下代码在我的asp.net mvc(C#)应用程序中设置一个cookie:
public static void SetValue(string key,string value,DateTime expires) { var httpContext = new HttpContextWrapper(HttpContext.Current); _request = httpContext.Request; _response = httpContext.Response; HttpCookie cookie = new HttpCookie(key,value) { Expires = expires }; _response.Cookies.Set(cookie); }
我需要在用户点击注销时删除Cookie。设置的Cookie不是使用清除/删除删除/删除。代码如下:
public static void Clear() { var httpContext = new HttpContextWrapper(HttpContext.Current); _request = httpContext.Request; _response = httpContext.Response; _request.Cookies.Clear(); _response.Cookies.Clear(); } public static void Remove(string key) { var httpContext = new HttpContextWrapper(HttpContext.Current); _request = httpContext.Request; _response = httpContext.Response; if (_request.Cookies[key] != null) { _request.Cookies.Remove(key); } if (_response.Cookies[key] != null) { _response.Cookies.Remove(key); } }
我已经尝试了两个以上的功能,但仍然cookie存在,当我尝试检查存在。
public static bool Exists(string key) { var httpContext = new HttpContextWrapper(HttpContext.Current); _request = httpContext.Request; _response = httpContext.Response; return _request.Cookies[key] != null; }
解决方法
清除响应的Cookie不会指示浏览器清除Cookie,它只是不会将Cookie发送回浏览器。要指示浏览器清除Cookie,您需要告诉它Cookie已过期,例如
public static void Clear(string key) { var httpContext = new HttpContextWrapper(HttpContext.Current); _response = httpContext.Response; HttpCookie cookie = new HttpCookie(key) { Expires = DateTime.Now.AddDays(-1) // or any other time in the past }; _response.Cookies.Set(cookie); }