如何从CookieCollection中删除cookie?

时间:2017-03-10 10:13:56

标签: c# .net-4.5.2

这是我的代码。它是一次获取/设置/删除多个cookie。设置和删除(全部)工作正常,但我无法从/** * @Route("/saveData") * @Method("POST") **/ public function saveDataAction (Request $request) { $data = $request->getContent(); $dataDecode = json_decode($data); if (is_object($dataDecode)) { try{ foreach ($dataDecode->customer as $customer) { //get data if ($something_is_wrong){ throw new \Exception('message'); } foreach ($dataDecode->location as $location) { //getdata if ($something_is_wrong){ throw new \Exception('message'); } foreach ($dataDecode->machine_1 as $machine_1) { //get and set data if ($something_is_wrong){ throw new \Exception('message'); } } foreach ($dataDecode->machine_2 as $machine_2) { //get and set data if ($something_is_wrong){ throw new \Exception('message'); } } foreach ($dataDecode->machine_3 as $machine_3) { //get and set data if ($something_is_wrong){ throw new \Exception('message'); } } } //These lines of code will only execute if no Exception is thrown: $em->createQuery('DELETE FROM AppBundle:Machine_1')->execute(); $em->createQuery('DELETE FROM AppBundle:Machine_2')->execute(); $em->createQuery('DELETE FROM AppBundle:Machine_3')->execute(); } catch (\Exception $e){ //These lines will only execute if something went wrong } } 删除过期的Cookie。

CookieCollection

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中删除过期的Cookie。怎么做? 如何从CookieCollection删除过期的Cookie?

enter image description here

在红色矩形线中,这是第一次点击获取Cookie 时过期的Cookie,它显示的是过期报告,但是第二次应该从{{{ 1}}。

2 个答案:

答案 0 :(得分:0)

只有为每个Cookie设置Expiry date才能清除Cookie。

此外,您可以尝试使用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();
    }
}

答案 1 :(得分:0)

找到固定的。

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();
        }
    }
}