我一直在尝试将清除HttpContext.Response
中的所有cookie的代码。
最初,我使用了以下方法:
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添加到Response
时,它也会被添加到`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
之间的关系到底是什么?
最佳答案
Request.Cookies
包含完整的cookie集合,包括浏览器发送到服务器的cookie和刚在服务器上创建的cookie。
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.
如果使
for
循环向后运行,则第一个代码示例应该可以工作。新的cookie将在结束后添加,因此向后循环将忽略它们。
关于asp.net - HttpContext.Request.Cookies和HttpContext.Response.Cookies之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4258467/