如何从 CookieCollection 中删除 cookie?

How to remove a cookie from CookieCollection?

这是我的代码。一次是 get/set/remove 多个 cookie。设置和删除(全部)工作正常,但我不能只从 CookieCollection.

中删除一个过期的 cookie
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using Newtonsoft.Json;

namespace SetGetMultipleCookies
{
    public partial class GetSetCookiesForm : Form
    {
        string readCookiesUrl = "http://test.dev/_test/cookies/readcookie.php";
        string setCookiesUrl = "http://test.dev/_test/cookies/setcookie.php";
        CookieContainer cookieHeader = new CookieContainer();
        CookieCollection cookie_collection = new CookieCollection();

        public GetSetCookiesForm()
        {
            InitializeComponent();
        }

        private void getCookiesButton_Click(object sender, EventArgs e)
        {
            // begins variable for page content.
            string pageSource;
            // send url request to web page.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.readCookiesUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            foreach (Cookie each_cookie in this.cookie_collection)
            {
                if (!each_cookie.Expired)
                {
                    request.Headers.Add("Cookie", each_cookie.ToString());
                } else
                {
                    // how to remove an expired cookie from cookie collection?

                }
            }

            // read the page content
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
            }

            // display debug.
            resultBox.Text = pageSource + "\r\n";
            foreach (Cookie each_cookie in this.cookie_collection)
            {
                resultBox.Text += each_cookie.ToString() + "; expires=" + each_cookie.Expires + "; path=" + each_cookie.Path + ";domain=" + each_cookie.Domain + "\r\n";
                if (each_cookie.Expired)
                {
                    resultBox.Text += "cookie expired.\r\n";
                }
            }
        }

        private void setCookiesButton_Click(object sender, EventArgs e)
        {
            // send url request to set cookie.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.setCookiesUrl);
            request.Method = "GET";
            request.CookieContainer = this.cookieHeader;
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // set cookies
            this.cookie_collection = response.Cookies;
            // debug
            resultBox.Text = "Headers ==========\r\n";
            foreach (string each_header in response.Headers)
            {
                resultBox.Text += each_header + " = " + response.Headers[each_header] + "\r\n";
            }
            resultBox.Text += "\r\nCookies (" + response.Cookies.Count + ") ==========\r\n";
            foreach (Cookie each_cookie in response.Cookies)
            {
                resultBox.Text += each_cookie.ToString() + "\r\n";
                resultBox.Text += each_cookie.Name + "\r\n";
                resultBox.Text += each_cookie.Value + "\r\n";
                resultBox.Text += each_cookie.Expires + "\r\n";
                resultBox.Text += each_cookie.Path + "\r\n";
                resultBox.Text += each_cookie.Domain + "\r\n";
                resultBox.Text += each_cookie.Secure + "\r\n";
                resultBox.Text += each_cookie.HttpOnly + "\r\n";
                resultBox.Text += each_cookie.Expired + "\r\n";
                resultBox.Text += "\r\n";
            }
            // get response body.
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                String responseText = reader.ReadToEnd();
                // json decode
                //LoginResponse responsej = JsonConvert.DeserializeObject<LoginResponse>(responseText);
                // display debug.
                resultBox.Text += "Response body ==========\r\n";
                resultBox.Text += responseText + "\r\n";
            }
        }

        private void removeCookiesButton_Click(object sender, EventArgs e)
        {
            this.cookieHeader = new CookieContainer();
            this.cookie_collection = new CookieCollection();

            resultBox.Text = "Logged out.";
        }
    }
}

getCookiesButton_Click 方法中,我只想从 CookieCollection 中删除一个过期的 cookie。怎么做? 如何从 CookieCollection?

中删除过期的 cookie

在红色矩形线中,这是第一次单击 获取 cookies 时的过期 cookie,它显示在那里并显示过期报告,这是正确的,但第二次应该将其删除完全来自 CookieCollection.

只能通过为每个 Cookie 设置 Expiry date 来清除它们。

此外,您可以尝试Clear()方法清除Cookies

// clear cookies server side
HttpContext.Current.Request.Cookies.Clear();

如果你想删除一个你已经知道的名字 Cookie,你可以像下面给出的那样设置 Expires 时间,当时间自动到达时 Cookie 将被移除。

if (Request.Cookies["cookiename"] != null)
{
    Response.Cookies["cookiename"].Expires = DateTime.Now.AddDays(-1);   
}

有时 Session 相关 Cookies 不会自动删除。为此,您可以尝试以下

HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

您可以编写一个单独的方法来执行此操作,如下所示

private void ExpireAllCookies()
{
    if (HttpContext.Current != null)
    {
        int cookieCount = HttpContext.Current.Request.Cookies.Count;
        for (var i = 0; i < cookieCount; i++)
        {
            var cookie = HttpContext.Current.Request.Cookies[i];
            if (cookie != null)
            {
                var cookieName = cookie.Name;
                var expiredCookie = new HttpCookie(cookieName) {Expires = DateTime.Now.AddDays(-1)};
                HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it
            }
        }

        // clear cookies server side
        HttpContext.Current.Request.Cookies.Clear();
    }
}

找到固定的。

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace SetGetMultipleCookies
{
    public partial class GetSetCookiesForm : Form
    {
        string readCookiesUrl = "http://test.dev/_test/cookies/readcookie.php";
        string setCookiesUrl = "http://test.dev/_test/cookies/setcookie.php";
        CookieContainer cookie_container = new CookieContainer();
        CookieCollection cookie_collection = new CookieCollection();


        public GetSetCookiesForm()
        {
            InitializeComponent();
        }


        private void getCookiesButton_Click(object sender, EventArgs e)
        {
            // begins variable for page content.
            string pageSource;
            // send url request to web page.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.readCookiesUrl);
            request.CookieContainer = this.cookie_container;
            request.UserAgent = "My C# App";

            // get response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // reset cookie collection.
            this.cookie_collection = new CookieCollection();
            // loop through cookie container to set only non-expired to cookie collection.
            var cookies_container = this.cookie_container.GetCookies(new Uri(this.readCookiesUrl));
            foreach (Cookie each_cookie in cookies_container)
            {
                if (!each_cookie.Expired)
                {
                    this.cookie_collection.Add(each_cookie);
                }

            }

            // read the page content
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
            }

            // display debug.
            resultBox.Text = pageSource.Replace("\n", "\r\n") + "\r\n";
            resultBox.Text += "\r\nCookies (" + this.cookie_collection.Count + ") ==========\r\n";
            foreach (Cookie each_cookie in this.cookie_collection)
            {
                resultBox.Text += each_cookie.ToString() + "; expires=" + each_cookie.Expires + "; path=" + each_cookie.Path + ";domain=" + each_cookie.Domain + "\r\n";
                if (each_cookie.Expired)
                {
                    resultBox.Text += "cookie expired.\r\n";
                }
            }

            // clear memory.
            pageSource = default(String);
            request = default(HttpWebRequest);
            response = default(HttpWebResponse);
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }


        private void setCookiesButton_Click(object sender, EventArgs e)
        {
            // send url request to set cookie.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.setCookiesUrl);
            request.Method = "GET";
            request.CookieContainer = this.cookie_container;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "My C# App";
            // get response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // set cookies collection
            this.cookie_collection = response.Cookies;

            // debug
            resultBox.Text = "Headers ==========\r\n";
            foreach (string each_header in response.Headers)
            {
                resultBox.Text += each_header + " = " + response.Headers[each_header].Replace("\n", "\r\n").Replace("\r", "\r\n") + "\r\n";
            }
            resultBox.Text += "\r\nCookies (" + this.cookie_collection.Count + ") ==========\r\n";
            foreach (Cookie each_cookie in this.cookie_collection)
            {
                resultBox.Text += each_cookie.ToString() + "\r\n";
                resultBox.Text += each_cookie.Name + "\r\n";
                resultBox.Text += each_cookie.Value + "\r\n";
                resultBox.Text += each_cookie.Expires + "\r\n";
                resultBox.Text += each_cookie.Path + "\r\n";
                resultBox.Text += each_cookie.Domain + "\r\n";
                resultBox.Text += each_cookie.Secure + "\r\n";
                resultBox.Text += each_cookie.HttpOnly + "\r\n";
                resultBox.Text += each_cookie.Expired + "\r\n";
                resultBox.Text += "\r\n";
                // add cookie to cookiecontainer
                this.cookie_container.Add(each_cookie);
            }
            // get response body.
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                String responseText = reader.ReadToEnd();
                // json decode
                //LoginResponse responsej = JsonConvert.DeserializeObject<LoginResponse>(responseText);// too lazy to do this.
                // display debug.
                resultBox.Text += "Response body ==========\r\n";
                resultBox.Text += responseText + "\r\n";
                // clear memory.
                reader = default(StreamReader);
                responseText = default(String);
            }

            // clear memory.
            request = default(HttpWebRequest);
            response = default(HttpWebResponse);
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }


        private void removeCookiesButton_Click(object sender, EventArgs e)
        {
            this.cookie_container = new CookieContainer();
            this.cookie_collection = new CookieCollection();

            resultBox.Text = "Logged out.";

            // clear memory.
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}