0

This is my code. It is get/set/remove multiple cookies at once. Set and remove (all) works fine but I can't remove just an expired cookie from 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.";
        }
    }
}

In the getCookiesButton_Click method, I just want to remove an expired cookie from CookieCollection. How to do that? How to remove an expired cookie from CookieCollection?

enter image description here

In the red rectangle line, that is the expired cookie first time when click on Get cookies it is showing there with expired report which is correct but second time it should be removed completely from the CookieCollection.

vee
  • 4,506
  • 5
  • 44
  • 81
  • What are you trying to do anyways? Why do all of it manually? Usually, that's not the way.. these classes are designed to work together behind the scenes. There's this CookieContainer class which often is all that you need - it handles caching cookies and handles removing expired ones and handles proper scoping of various cookies to corect URLs. All you need to "handle cookies" is to create the CookieContainer, and a WebClient instance, set it to use the cookie container and then use the webclient to create requests. It will even follow redirects and do all that boring things for you. – quetzalcoatl Mar 10 '17 at 10:45
  • 1
    ~> http://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class etc? – quetzalcoatl Mar 10 '17 at 10:49
  • @quetzalcoatl I want to create client program that have connections with web server using Rest API. It uses many cookies such as logins, some setting values. I'm new to VC# and C# language so I'm not familiar with these and don't know which is the best way to handle with cookies. There are not much example and tutorial about this too. Thank you anyway. I will try it soon. – vee Mar 10 '17 at 12:01

2 Answers2

0

Cookies can be cleaned only by setting the Expiry date for each of them.

Also, You can try Clear() method to clear Cookies

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

If you want to remove a Cookie which name already known to you, you can set the Expires time like given below such that when the time reaches automatically the Cookie will be removed.

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

Sometimes Session related Cookies will not remove automatically. For that you can try below one

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

You can write a separate method to do that also like below

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();
    }
}
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
  • No, I means just "an expired cookie" (each cookie that expired). Please look in getCookiesButton_Click method NOT removeCookiesButton_Click – vee Mar 10 '17 at 10:20
  • .Expires or .Expired did not remove, it just tell the program that it was expired. when I click on get cookies again I want it disappeared from the collection, only available non-expired. – vee Mar 10 '17 at 10:24
  • I have just update the question with complete details. It is windows form not web app (asp.net) and those .Expires, .Expired, or even HttpContext will not work. It just needs to remove from the list like delete an array key but I don't know how because I'm new to this. – vee Mar 10 '17 at 10:37
0

Found the fixed.

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();
        }
    }
}
vee
  • 4,506
  • 5
  • 44
  • 81