HttpListener Issues: Each HTTP request results in two contexts returned by the HttpListener

I put together a small embedded HTTP server in a Windows application that listens for updates coming from other devices on the network that speak HTTP.

For each HTTP request, the code that processes the request / response is executed twice, I expect it to be run only once. I tried the code using the AsyncGetContext method and used the synchronous version of GetContext - the end result is the same.

code

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(); } 

Is there something obvious that I was missing, I did not have enough ideas to identify the problem.

+4
source share
1 answer

Well, the problem is that I used a web browser to check the HTTP connection, and by default the web browser also sends a request for favicon.ico. Thus, two queries actually appeared. Thanks @Inuyasha for suggesting checking things out with Wireshark.

+10
source

All Articles