最初,我使用了这个:
DateTime cookieExpires = DateTime.Now.AddDays(-1); for (int i = 0; i < HttpContext.Request.Cookies.Count; i++) { HttpContext.Response.Cookies.Add( new HttpCookie(HttpContext.Request.Cookies[i].Name,null) { Expires = cookieExpires }); }
但是,这将导致OutOfMemoryException错误,因为for循环永远不会退出 – 每次向响应中添加一个cookie时,它也会被添加到`Request.
以下方法有效:
DateTime cookieExpires = DateTime.Now.AddDays(-1); List<string> cookieNames = new List<string>(); for (int i = 0; i < HttpContext.Request.Cookies.Count; i++) { cookieNames.Add(HttpContext.Request.Cookies[i].Name); } foreach (string cookieName in cookieNames) { HttpContext.Response.Cookies.Add( new HttpCookie(cookieName,null) { Expires = cookieExpires }); }
那么,HttpContext.Request.Cookies和HttpContext.Response.Cookies之间的关系到底是什么?
解决方法
Response.Cookies
包含服务器将发回的cookie.
此集合开始为空,应更改为修改浏览器的cookie.
文件说明:
ASP.NET includes two intrinsic cookie
collections. The collection accessed
through the Cookies collection of
HttpRequest contains cookies
transmitted by the client to the
server in the Cookie header. The
collection accessed through the
Cookies collection of HttpResponse
contains new cookies created on the
server and transmitted to the client
in the Set-Cookie header.After you add a cookie by using the
HttpResponse.Cookies collection,the
cookie is immediately available in the
HttpRequest.Cookies collection,even
if the response has not been sent to
the client.