2014-01-24 72 views
4

我正在構建一個代理服務器來處理本地請求。
例如 - 捕獲網絡瀏覽器打印請求並將其發送到相應的LAN打印機。
到目前爲止,我的想法是在Windows服務中託管FiddlerCore引擎。
這是我的代碼:發送HTTP到本地FiddlerCore

private static void Main() 
{ 
    FiddlerApplication.OnNotification += (sender, e) => Console.WriteLine("** NotifyUser: " + e.NotifyString); 
    FiddlerApplication.Log.OnLogString += (sender, e) => Console.WriteLine("** LogString: " + e.LogString); 
    FiddlerApplication.BeforeRequest += oSession => { Console.WriteLine("Before request for:\t" + oSession.fullUrl); oSession.bBufferResponse = true; ParseRequest(oSession); }; 
    FiddlerApplication.BeforeResponse += oSession => Console.WriteLine("{0}:HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl); 
    FiddlerApplication.AfterSessionComplete += oSession => Console.WriteLine("Finished session:\t" + oSession.fullUrl); 

    Console.CancelKeyPress += Console_CancelKeyPress; 
    Console.WriteLine("Starting FiddlerCore..."); 
    CONFIG.IgnoreServerCertErrors = true; 
    FiddlerApplication.Startup(8877, true, true); 
    Console.WriteLine("Hit CTRL+C to end session."); 

    Object forever = new Object(); 
    lock (forever) 
    { 
     Monitor.Wait(forever); 
    } 
} 

private static void ParseRequest(Session oSession) 
{ 
    switch (oSession.host) 
    { 
     case "localhost.": 
      Console.WriteLine("Handling local request..."); 
      break; 
    } 
} 

private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) 
{ 
    Console.WriteLine("Shutting down..."); 
    FiddlerApplication.Shutdown(); 
    Thread.Sleep(750); 
} 

我的問題:
ParseRequest功能可識別本地請求(即http://localhost./print?whatever),但我怎麼可以轉發中繼他們停止代理(解析並執行打印請求,但沒有得到404頁面)?

回答

5

實測溶液自己:

BeforeRequest回調,一個Fiddler.Session對象被作爲參數傳遞。
當調用它的utilCreateResponseAndBypassServer函數時,請求不會中繼到任何服務器,而是在本地處理。

所以,我的新ParseRequest功能如下:

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

    Console.WriteLine("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"; 
    oSession.utilSetResponseBody("<html><body>Handling local request...</body></html>"); 
} 
+0

是啊,這是正確的做法。 – EricLaw

+0

謝謝,我看到你幫助許多人與提琴手,所以你的確認幫助我。 – toy4fun