我正在使用这段代码来实现 Http 服务器:
public Server()
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(Server.UriAddress);
StartServer();
}
public void StartServer()
{
_httpListener.Start();
while (_httpListener.IsListening)
ProcessRequest();
}
void ProcessRequest()
{
var result = _httpListener.BeginGetContext(ListenerCallback, _httpListener);
result.AsyncWaitHandle.WaitOne();
}
void ListenerCallback(IAsyncResult result)
{
HttpListenerContext context = _httpListener.EndGetContext(result);
HttpListenerRequest request = context.Request;
string url = request.RawUrl;
url = url.Substring(1, url.Length - 1);
HttpListenerResponse response = context.Response;
string responseString = url;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
我有一个问题,如果我在浏览器中写这个(这是一个例子,每次调用都会发生):
http://localhost:8888/Hello%20World
ListenerCallback
方法被调用了两次,知道如何解决吗?
最佳答案
一个答案已经被接受了,但我认为它可能对后续的其他人仍然有用。
默认情况下,给定 URL 的大多数浏览器将至少进行两次调用。一个调用请求 URL,另一个调用 favicon.ico。
因此应该在 ListenerCallback 中进行检查,例如
HttpListenerContext context = _httpListener.EndGetContext(result);
HttpListenerRequest request = context.Request;
string url = request.RawUrl;
url = url.Substring(1);
if (url == "favicon.ico")
{
return;
}
//normal request handling code
我希望这对某人有帮助。
关于c# - HttpListener 调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15948750/