如何将CookieContainer转换为字符串?

时间:2016-07-21 20:57:11

标签: c# string converter cookiecontainer

我尝试循环cookie容器循环,但返回错误。如何正确转换CookieContainerstring

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

错误2 foreach语句不能用于类型的变量   “System.Net.CookieContainer”,

2 个答案:

答案 0 :(得分:2)

如果您只对特定域的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提供的反射。

答案 1 :(得分:0)

示例:

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