【问题标题】:HttpListener problems: Each HTTP request results in two contexts returned by HttpListenerHttpListener 问题:每个 HTTP 请求都会导致 HttpListener 返回两个上下文
【发布时间】:2011-10-15 23:10:39
【问题描述】:

我已经在一个 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();
}

有什么明显的我遗漏的吗,我已经没有办法追查这个问题了。

【问题讨论】:

  • 绝对确定只有一个请求吗?通过在运行测试时观看 Wireshark 来加倍确定。
  • 您可能还想看看 OpenRasta,它会为您完成所有这些 ;-) - 我们已经成功地使用它在各种应用程序中嵌入 HTTP 侦听器作为应用程序的核心并作为监控等的螺栓 - github.com/openrasta/openrasta-stable/wiki
  • @Inuyasha,这就是问题所在,网络浏览器也发送了对 favicon.ico 的请求。

标签: c# http asynchronous httplistener


【解决方案1】:

好的,问题是我使用 Web 浏览器测试 HTTP 连接,默认情况下,Web 浏览器也会发送对 favicon.ico 的请求。所以实际上遇到了两个请求。感谢@Inuyasha 建议我使用 Wireshark 进行检查。

【讨论】:

  • 天哪,这让我很困扰。
  • 你最后是怎么处理这个问题的?也就是说,有没有办法对用户的单个网页请求只响应一次(即使从技术上讲是 2 个请求)?
  • @danns87,您必须同时处理这两个请求 - 只需检测您不想处理的任何内容(例如网站图标)并返回 404 错误。或者实际上返回一个网站图标。
猜你喜欢
  • 1970-01-01
  • 2015-04-06
  • 2023-04-01
  • 2012-01-20
  • 2014-12-17
  • 2011-12-29
  • 2013-10-18
  • 2012-02-20
相关资源
最近更新 更多