【发布时间】: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