加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – HttpContext.Request.Cookies和HttpContext.Response

发布时间:2020-12-16 03:36:52 所属栏目:asp.Net 来源:网络整理
导读:我一直在试验清除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(HttpC
我一直在试验清除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将在结束后添加,因此向后循环将忽略它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读