2013-07-29 74 views
2

我在WebClient類中的Headers集合中發現了奇怪的問題。請求後在WebClient中消失標題

這是我的例子:

WebClient client = new WebClient(); 
     client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0"); 
     client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
     client.Headers.Add("Accept-Language", "pl,en-us;q=0.7,en;q=0.3"); 

     Console.WriteLine("Before request:"); 
     foreach (string key in client.Headers) 
     { 
      Console.WriteLine(key + ": " + client.Headers[key]); 
     } 

     client.DownloadString("http://www.google.com"); 

     Console.WriteLine(); 
     Console.WriteLine("After request:"); 

     foreach (string key in client.Headers) 
     { 
      Console.WriteLine(key + ": " + client.Headers[key]); 
     } 

     Console.ReadLine(); 

我運行這個簡單的程序的結果是:

Before request: 
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: pl,en-us;q=0.7,en;q=0.3 

After request: 
Accept-Language: pl,en-us;q=0.7,en;q=0.3 

爲什麼我的頭正在消失?

回答

3

因爲標頭已發送,webclient完成了其工作。如果你想爲下一個請求使用相同的頭文件,你應該再次添加它們。