2010-06-29 81 views
16

我需要在我的路由器中讀取一個位置,但我得到以下異常 - ServerProtocolViolation「服務器提交了違反協議的情況,Section = ResponseHeader Detail = CR後面必須跟LF」C#:處理WebClient「違反協議」

這發生在我使用.DownloadString(url)函數時。有沒有辦法讓WebClient忽略協議違規?谷歌搜索告訴我,我應該在某處設置useUnsafeHeaderParsing選項。我可以通過程序來完成嗎?如果我使用它,有什麼收穫?

編輯:附加代碼 -

public Readlog() { 
     WebClient wc = new WebClient(); 

     string url = @"http://192.168.0.1/setup.cgi?next_file=log.htm&todo=cfg_init"; 
     Console.WriteLine(url); 
     try { 
      //wc.Headers.Add("User-Agent", "Mozilla/5.0(Windows; U; Windows NT 5.2; rv:1.9.2) Gecko/20100101 Firefox/3.6"); 
      wc.Credentials = new NetworkCredential("admin", "admin"); 
      //Next line causes exception System.Net.WebException 
      //Message - "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF" 
      //May be I need to use useUnsafeHeaderParsing somehow to avoid that 
      string result = wc.DownloadString(url); 
      Console.WriteLine(result); 
     } catch (WebException we) { 
      System.Diagnostics.Trace.WriteLine(we.ToString()); 
     } 
    } 
+0

您可能希望將代碼粘貼到您的問題中。 – 2010-06-29 15:55:05

回答

21

看起來像最簡單的方法,包括用含有下列您的應用程序.config文件:

<system.net> 
<settings> 
<httpWebRequest useUnsafeHeaderParsing = "true"/> 
</settings> 
</system.net> 

但是它也可以內做到這一點代碼,但它似乎有點凌亂:

http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/ff098248-551c-4da9-8ba5-358a9f8ccc57

還要注意的是該屬性的MSDN定義

設置該屬性忽略期間 HTTP分析發生 驗證錯誤。

http://msdn.microsoft.com/en-us/library/system.net.configuration.httpwebrequestelement.useunsafeheaderparsing.aspx

所以我會說這是相當安全的使用,雖然它不遑只用它的向後兼容性。

+0

我覺得你可以用另一種方式做到這一點。我的直覺說服務點經理或subglassing HttpWebRequest – 2010-06-30 05:22:49

+6

謝謝,它的工作原理,雖然它是凌亂的,如你所說。這應該與在WebClient類中設置屬性一樣簡單。微軟決定採用(幾乎)硬編碼來遵守RFC是非常值得懷疑的 - 它應該對程序開放。這幾乎看起來像是一種短視 - 認爲程序員總是有權修復服務器端協議違規。 – KalEl 2010-06-30 13:02:20

0

我在我自己的網絡服務器這個問題,在頭我改變

HTTP/1.x 200 OK 

HTTP/1.0 200 OK 

現在的作品時,我使用的瀏覽器(chorome或...),或在Web客戶端(c#)

相關問題