2014-02-27 97 views
0

我正在捕獲本地POST請求並解析其數據。
僅供測試使用,FiddlerCore只能響應已解析的數據。
這裏的FidlerCore封裝代碼:使用FiddlerCore解析POST請求數據

private void FiddlerApplication_BeforeRequest(Session oSession) 
{ 
    if (oSession.hostname != "localhost") return; 

    eventLog.WriteEntry("Handling local request..."); 
    oSession.bBufferResponse = true; 
    oSession.utilCreateResponseAndBypassServer(); 
    oSession.oResponse.headers.HTTPResponseStatus = "200 Ok"; 
    oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8"; 
    oSession.oResponse["Cache-Control"] = "private, max-age=0"; 

    string body = oSession.GetRequestBodyAsString(); 
    oSession.utilSetResponseBody(body); 
} 

這裏的請求發送方的代碼:

const string postData = "This is a test that posts this string to a Web server."; 

try 
{ 
    WebRequest request = WebRequest.Create("http://localhost/?action=print"); 
    byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
    request.ContentLength = byteArray.Length; 
    request.ContentType = "text/html"; 
    request.Method = "POST"; 

    using (Stream stream = request.GetRequestStream()) 
    { 
     stream.Write(byteArray, 0, byteArray.Length); 
    } 

    using (WebResponse response = request.GetResponse()) 
    { 
     txtResponse.Text = ((HttpWebResponse)response).StatusDescription; 
     using (Stream stream = response.GetResponseStream()) 
     { 
      using (StreamReader streamReader = new StreamReader(stream)) 
      { 
       string responseFromServer = streamReader.ReadToEnd(); 
       streamReader.Close(); 
       txtResponse.Text = responseFromServer; 
      } 
     } 
    } 
} 
catch (Exception ex) 
{ 
    txtResponse.Text = ex.Message; 
} 

,我發現了以下錯誤:

The server committed a protocol violation. Section=ResponseStatusLine

我是什麼做錯了?

+0

您知道如何獲取Fiddler.Session對象中的請求有效內容嗎? – Cher

回答

0

得到它通過改變工作:

WebRequest request = WebRequest.Create("http://localhost/?action=print"); 

WebRequest request = WebRequest.Create("http://localhost:8877/?action=print"); 

從瀏覽器被FiddlerCore正確攔截,而無需指定端口號調用這個URL。我不認爲我應該插入監聽端口,因爲FiddlerCore應該攔截所有的流量,對吧?

+0

Fiddler捕獲客戶端設置爲將其用作代理的所有請求。 .NET應用程序可能會或可能不會採用系統的代理設置(並且不顯示是否已將FiddlerCore配置爲註冊爲系統代理)。通過指定端口,您可以直接有效地使用FiddlerCore作爲反向代理。 – EricLaw

+0

我確實將FiddlerCore註冊爲系統代理,就像這樣 - 「FiddlerApplication.Startup(8877,true,true);'但由於它駐留在Windows服務中,所以它的行爲有所不同。在啓動服務時,它不會像設置Windows應用程序時那樣設置瀏覽器的代理設置。因此,當嘗試調用本地方法時,爲了處理服務,我注意到我必須包含端口號,即使從瀏覽器調用它時也是如此 - 「http:// localhost:8877 /?Action = Print&PrinterID = Printer1'。 – toy4fun

+0

@EricLaw我想我明白髮生了什麼 - 持有FiddlerCore的服務正在使用LocalSystem帳戶,並將FiddlerCore註冊到此帳戶,但用戶正在使用自己的帳戶。如何使用用戶帳戶註冊FiddlerCore而不是服務帳戶? – toy4fun