[英]400 Bad Request (Invalid Host) using simple webserver in C#
我有一個小的C#控制台應用程序作為網絡服務器。 它對同一網絡中的設備的NAT響應很好,但是當我嘗試從外部IP在瀏覽器中訪問它時,我得到400。
路由器配置為端口轉發,否則我得到404。
localhost:8888 / test工作正常。 也適用於任何設備的192.168.0.x:8888 / test。
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);
}
}
}
Webserver類:
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)效果很好!
和@ sean-bradley有類似的問題 - 但是在.net上。
這非常有效:
WebServer ws = new WebServer(SendResponse, "http://+:80/");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.