gpt4 book ai didi

asp.net - HttpContext.Request.Cookies和HttpContext.Response.Cookies之间的关系

转载 作者:行者123 更新时间:2023-12-04 13:44:20 25 4
gpt4 key购买 nike

我一直在尝试将清除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.CookiesHttpContext.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com