C#HTTP错误400-主机名Simple HTTP侦听器无效


using System.Net;
using System.Text;
namespace HttpServer
{
class Program
{
// Main method
static void Main()
{
using var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:10060/");
listener.Start();
Console.WriteLine("Listening on port 10060...");
// Request handler
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest req = context.Request;
Console.WriteLine($"Received request for {req.Url}");
// TODO: Login stuff
Uri? url = req.Url;
if (url.ToString() == "http://localhost:10060/login")
{
using HttpListenerResponse resp = context.Response;
resp.Headers.Set("Content-Type", "text/plain");
string data = "Hello there!";
byte[] buffer = Encoding.UTF8.GetBytes(data);
resp.ContentLength64 = buffer.Length;
using Stream ros = resp.OutputStream;
ros.Write(buffer, 0, buffer.Length);
}
}
}
}
}

上面的代码是一个简单的http服务器,用于侦听请求。当在浏览器中转到localhost:10060时,上面的代码就可以工作了。但是,我想通过不同的设备通过同一网络上的机器IP地址访问此服务器。这样做时,会由于主机名无效而导致错误的请求。有办法解决这个问题吗?

尝试使用ip地址而不是localhost。或尝试*:10060

在另一台机器中,尝试修改防火墙规则以允许端口80。

  1. 在本地计算机上具有高级安全性的Windows防御防火墙
  2. 入站规则
  3. 新规则
  4. 选择端口,下一步,TCP,特定本地端口,类型80
  5. 允许连接并保存规则

让我们知道这是否有效。