【问题标题】:HttpListener accepts 2 times for each connection?HttpListener 每个连接接受 2 次?
【发布时间】:2021-07-25 14:50:23
【问题描述】:

我正在使用 VS2019 测试 C# HttpListener,.net core 3.1 的控制台应用程序

首先,我在管理员模式下使用了powershell并运行:

> netsh http add urlacl url=http://+:80/ user=everyone

然后我的C#程序如下:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("...Wait until all async finish");
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(@"http://+:80/");
        listener.Start();
        while (true)
        {
            Console.WriteLine("Wait one connection");
            var context = listener.GetContext();
            var response = context.Response;
            Console.WriteLine("... Got one connection response");
            var responseString = $"<html><body><h1>Hellow,How are You?{DateTime.Now}</h1></body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            using (var stream = response.OutputStream)
            {
                stream.Write(buffer, 0, buffer.Length);
            }
            Console.WriteLine("Response done\n");
        }
    }
}

问题是,每次我使用 edge 或 chrome 浏览“localhost”时,while 循环都会运行 2 次,并打印两次“Response done”行。

我希望每次为“localhost”创建新的浏览器标签或刷新页面时,我的程序应该只进入一次 while 循环。那么问题是什么?

非常感谢。

【问题讨论】:

    标签: c# .net-core connection httplistener


    【解决方案1】:

    浏览器发出额外请求以获取您网页的 favicon.ico。
    您可以在浏览器的“网络”选项卡中验证发送到 HttpListener 的请求:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 2014-09-27
      • 1970-01-01
      • 2011-07-17
      • 2020-12-23
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多