如何将 CookieContainer 转换为字符串?

How convert CookieContainer to string?

我尝试使用循环来循环 cookie 容器,但它 return 错误。如何正确地将 CookieContainer 转换为 string

foreach (Cookie item in cookieContainer)
{
    var data = item.Value + "=" + item.Name;
}

Error 2 The foreach statement can not be used for variables of type "System.Net.CookieContainer",

如果您只对特定域的 cookie 感兴趣,则可以使用 GetCookies() 方法进行迭代。

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
}

如果您有兴趣获取所有 cookie,那么您可能需要使用 this answer 提供的反射。

样本:

public static void Main(string[] args)
    {   
        if (args == null || args.Length != 1)
        {
            Console.WriteLine("Specify the URL to receive the request.");
            Environment.Exit(1);
        }
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
        request.CookieContainer = new CookieContainer();

        HttpWebResponse response = (HttpWebResponse) request.GetResponse();



        // Print the properties of each cookie.
        foreach (Cookie cook in response.Cookies)
        {                    
            // Show the string representation of the cookie.
            Console.WriteLine ("String: {0}", cook.ToString());
        }
    }