How to get cookies info inside of a CookieContainer? (All Of Them, Not For A Specific Domain)
reflection can be used to get the private field that holds all the domain key in CookieContainer object,
Q. How do i got the name of that private field ?
Ans. Using Reflector;
its is declared as :
private Hashtable m_domainTable;
once we get the private field, we will get the the domain key, then getting cookies is a simple iteration.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Net;
using System.Collections;
namespace ConsoleApplication4
{
static class Program
{
private static void Main()
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Cookie("name1", "value1", "/", "domain1.com"));
cookies.Add(new Cookie("name2", "value2", "/", "domain2.com"));
Hashtable table = (Hashtable)cookies.GetType().InvokeMember(
"m_domainTable",
BindingFlags.NonPublic |
BindingFlags.GetField |
BindingFlags.Instance,
null,
cookies,
new object[]{}
);
foreach (var key in table.Keys)
{
Uri uri = new Uri(string.Format("http://{0}/", key));
foreach (Cookie cookie in cookies.GetCookies(uri))
{
Console.WriteLine("Name = {0} ; Value = {1} ; Domain = {2}",
cookie.Name, cookie.Value, cookie.Domain);
}
}
Console.Read();
}
}
}
How can I get all Cookies of a CookieContainer?
A solution using reflection:
public static CookieCollection GetAllCookies(CookieContainer cookieJar)
{
CookieCollection cookieCollection = new CookieCollection();
Hashtable table = (Hashtable) cookieJar.GetType().InvokeMember("m_domainTable",
BindingFlags.NonPublic |
BindingFlags.GetField |
BindingFlags.Instance,
null,
cookieJar,
new object[] {});
foreach (var tableKey in table.Keys)
{
String str_tableKey = (string) tableKey;
if (str_tableKey[0] == '.')
{
str_tableKey = str_tableKey.Substring(1);
}
SortedList list = (SortedList) table[tableKey].GetType().InvokeMember("m_list",
BindingFlags.NonPublic |
BindingFlags.GetField |
BindingFlags.Instance,
null,
table[tableKey],
new object[] { });
foreach (var listKey in list.Keys)
{
String url = "https://" + str_tableKey + (string) listKey;
cookieCollection.Add(cookieJar.GetCookies(new Uri(url)));
}
}
return cookieCollection;
}
.NET 6 Update
Finally, .NET 6 was released and introduced the CookieContainer.GetAllCookies()
method which extracts the CookieCollection
- Documentation link.
public System.Net.CookieCollection GetAllCookies();
How convert CookieContainer to string?
If you are only interested in the cookies for a specific domain, then you can iterate using the GetCookies() method.
var cookieContainer = new CookieContainer();
var testCookie = new Cookie("test", "testValue");
var uri = new Uri("https://www.google.com");
cookieContainer.Add(uri, testCookie);
foreach (var cookie in cookieContainer.GetCookies(uri))
{
Console.WriteLine(cookie.ToString()); // test=testValue
}
If your interested in getting all the cookies, then you may need to use reflection as provided by this answer.
Why CookieContainer does not replace cookies with the same name?
It's a bug in dotnet runtime: https://github.com/dotnet/runtime/issues/60628
Pending PR: https://github.com/dotnet/runtime/pull/64038
retrieve data inside cookieContainer in java
I just find out the reason why, my cookie domain set wrong way.
Here the new test Code I just fix. Hope this help who have the same problem in the future ( Of cause it must be great if no one face this silly problem )
private HttpWebRequest request(){
try{
System.Uri uri = new System.Uri("http://localhost:8080/...");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Timeout = 15000;
request.KeepAlive = true ;
request.Method= "GET";
Cookie Authentication = new Cookie("Session" , "09iubasd");
Authentication.Domain = uri.Host;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(Authentication);
request.Headers.Add("testting", "hascome");
return request;
}catch(System.Exception ex){
Debug.Log("[Exception]" + ex);
throw ex;
}
}
Cookie for domain not being used for subdomains
As I couldn't find an answer to this (not in TechNet either), I decided to go with the following solution, which works, but not sure if there is a proper way of solving the issue:
foreach (Cookie cookie in cookies.GetCookies(new Uri("https://dev.example.com")))
{
cookies.Add(new Uri("https://accounts.dev.example.com"), new Cookie(cookie.Name, cookie.Value, cookie.Path, ".accounts.dev.example.com"));
}
So, I'm duplicating the cookie for each one of the subdomains that my app should send these cookies to.
How to remove cookies under 1 domain in CookieContainer
You could do something like this.
CookieContainer c = new CookieContainer();
var cookies = c.GetCookies(new Uri("http://www.google.com"));
foreach (Cookie co in cookies)
{
co.Expires = DateTime.Now.Subtract(TimeSpan.FromDays(1));
}
This will expire all cookies for the domain you specify.
Related Topics
Using Linq to Groupby and Sum Datatable
How to Format a String as a Telephone Number in C#
How to Get Only Date from a Datetime Value in Razor Page
How to Get the Display Name Attribute of an Enum Member Via MVC Razor Code
Convert Date Format of String to Datetime Mm/Dd/Yyyy When System Date Formate Is Dd/Mm/Yyyy
Httpclient Post With Parameters in Body
Discord.Net C# 1.0.2 How to Send Messages to Specific Channels
Convert Character to Its Alphabet Integer Position
Easiest Way to Check If an Arbitrary String Is a Valid Filename
Choosing the Default Value of an Enum Type Without Having to Change Values
How to Validate a Datetime in C#
Console.Writeline Does Not Show Up in Output Window
Deserialize Json String in to Multiple C# Objects
Convert Time With Milliseconds to Datetime in C#
Convert Time-Formatted Column in Excel to C# Datetime
C# String to Hex , Hex to Byte Conversion
Httpcontext.Current.Request.Files Is Always Empty
Create Global Variable in .Net Core 2.0 to Use in Razor Views