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

标签 asp.net cookies request response httpcontext

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

相关文章:

php - Laravel:为什么我的 ajax 请求返回 "500 (Internal Server Error)"?

c# - ASP.NET MVC WebAPI 404 错误

c# - 发布表单但不发布 View 状态

asp.net - 生成本地资源后缺少服务器标签

javascript - Angularjs:为什么页面刷新会破坏 $rootScope 的值?

javascript - 如何从浏览器获取从另一个应用程序删除的 cookie

node.js - 问 : Hot to change Ip in request using tor-request npm

c# - asp.net 按钮悬停不起作用

asp.net - 让 ASP.NET Cookieless Session 和 JQuery AJAX 完美结合

HTTP 请求/响应流程