400 错误请求(无效主机)在 C# 中使用简单的 Web 服务器
本文关键字:简单 服务器 Web 请求 错误 无效 主机 | 更新日期: 2023-09-27 18:36:14
我有一个小型的C#控制台应用程序作为Web服务器。它在同一网络中的设备在NAT上响应良好,但是当我尝试从外部IP在浏览器中访问它时,我得到了400。
路由器配置为端口转发,否则我得到404。
本地主机:8888/测试工作正常。还有 192.168.0.x:8888/测试任何设备。
xxx.xxx.xxx.xxx:8888/test 失败,并显示 HTTP 错误 400。请求主机名无效。
有什么建议吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace httpsrv
{
class Program
{
static void Main(string[] args)
{
WebServer ws = new WebServer(SendResponse, "http://localhost:8888/test/");
ws.Run();
Console.WriteLine("Pi server started");
Console.ReadKey();
ws.Stop();
}
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>Hosted from rasp. pi!<br>{0}</BODY></HTML>", DateTime.Now);
}
}
}
网络服务器类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace httpsrv
{
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { }
finally
{
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { }
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}
在使用自托管 OWIN 和 c# 时,我在 ubuntu 上遇到了这个问题。我通过将.exe内设置的基址设置为
http://*:80
而不是
http://192.168.1.1:80
WebServer ws = new WebServer(SendResponse, "http://*:80/");
加上使用"以管理员身份运行"模式启动应用程序(或命令提示符/Visual Studio)效果很好!
- 您的 DNS 或名称解析不正确。
- 没有路由可以将该流量转发到您的 Web 服务器
- 检查端口转发 您应该将端口 8888 转发到内部 IP
- 最后但并非最不重要的是检查您的防火墙,它应该允许端口 8888
- 查看您的代码,似乎您正在对请求进行硬编码,将其设置为变量,以便您可以即时更改它
与 @sean-bradley 有类似的问题 - 但在 .net 上。
这工作得很好:
WebServer ws = new WebServer(SendResponse, "http://+:80/");