HttpListener问题:每个HTTP请求都会导致HttpListener返回两个上下文

Bry*_*ein 4 c# asynchronous http httplistener

我一直在Windows服务应用程序中组装一个小的嵌入式HTTP服务器,该应用程序监听来自网络上使用HTTP的其他设备的更新.

对于每个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();
}
Run Code Online (Sandbox Code Playgroud)

是否有任何明显的遗漏,我已经没有想法来追查这个问题.

Bry*_*ein 10

好吧,问题是我使用Web浏览器测试HTTP连接,默认情况下,Web浏览器也会发送favicon.ico请求.所以实际上有两个请求.感谢@Inuyasha建议我和Wireshark一起检查.