微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我一直在试验清除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时,它也会被添加到`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将在结束后添加,因此向后循环将忽略它们.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐