2011-10-15 26 views
4

我一直在一個小型嵌入式HTTP服務器放在一個Windows服務應用程序中,該應用程序偵聽來自網絡上說HTTP的其他設備的更新。HttpListener問題:每個HTTP請求都會導致HttpListener返回兩個上下文

對於每個HTTP請求,處理請求/響應的代碼被執行兩次,我期望它只運行一次。我嘗試使用AsyncGetContext方法和使用同步版本GetContext的代碼 - 最終結果是相同的。

代碼

public void RunService() 
{ 
    var prefix = "http://*:4333/"; 
    HttpListener listener = new HttpListener(); 
    listener.Prefixes.Add(prefix); 
    try 
    { 
     listener.Start(); 
     _logger.Debug(String.Format("Listening on http.sys prefix: {0}", prefix)); 
    } 
    catch (HttpListenerException hlex) 
    { 
     _logger.Error(String.Format("HttpListener failed to start listening. Error Code: {0}", hlex.ErrorCode)); 
     return; 
    } 
    while (listener.IsListening) 
    { 
     var context = listener.GetContext(); // This line returns a second time through the while loop for each request 
     ProcessRequest(context); 
    } 
    listener.Close(); 
} 

private void ProcessRequest(HttpListenerContext context) 
{ 
    // Get the data from the HTTP stream 
    var body = new StreamReader(context.Request.InputStream).ReadToEnd(); 
    _logger.Debug(body); 

    byte[] b = Encoding.UTF8.GetBytes("OK"); 
    context.Response.StatusCode = 200; 
    context.Response.KeepAlive = false; 
    context.Response.ContentLength64 = b.Length; 

    var output = context.Response.OutputStream; 
    output.Write(b, 0, b.Length); 
    output.Close(); 
    context.Response.Close(); 
} 

有什麼明顯的,我很想念,我已經江郎才盡追查問題。

+1

你*絕對*確定只有一個請求?通過在運行測試時觀察Wireshark來加倍確保。 – Amy

+0

您可能還想看看OpenRasta,它爲您完成所有這些工作;-) - 我們已經成功地使用它將HTTP偵聽器嵌入到各種應用程序中,作爲應用程序的核心和用於監視等 - https://github.com/openrasta/openrasta-stable/wiki –

+0

@Inuyasha,這是問題,網絡瀏覽器也發送favicon.ico的請求。 –

回答

10

好的,問題是我使用網絡瀏覽器來測試HTTP連接,默認情況下,Web瀏覽器也會發送一個favicon.ico請求。所以兩個請求實際上正在出現。感謝@Inuyasha建議我用Wireshark檢查一下。

+0

廢話,這是困擾我。 –

+0

你是如何處理這個問題的?也就是說,對於來自用戶的單個網頁請求(即使技術上是2個請求),是否有一種方法只響應一次? – danns87

+0

@ danns87,你必須處理這兩個請求 - 只要檢測你不需要處理的任何內容(如favicon)並返回一個404錯誤。或者實際上返回一個favicon。 – Miral