2016-07-21 37 views
0

Ich versuche Loop-Cookie-Container mit Schleife, aber seine Rückkehr Fehler. Wie richtig konvertieren CookieContainer-stringWie CookieContainer in Zeichenfolge konvertieren?

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

Fehler 2 Die foreach-Anweisung kann nicht für Variablen vom Typ „System.Net.CookieContainer“,

Antwort

1

Wenn Sie daran interessiert sind nur in die verwendet werden, Cookies für eine bestimmte Domäne, dann können Sie mit der GetCookies() -Methode iterieren.

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 
} 

Wenn Ihr Interesse an alle Cookies bekommen, dann müssen Sie Reflektion verwenden, wie durch this answer zur Verfügung gestellt.

0

Probe:

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