首页 > 解决方案 > Http 服务器给出错误 400 c# .net 框架

问题描述

我想制作一个http服务器进行测试。为此,我正在使用 HttpListener 类。

HttpListener listener = new HttpListener();
                listener.Prefixes.Add("http://localhost:24578/");
                while (true)
                {
                    listener.Start();
                    HttpListenerContext context = listener.GetContext();
                    HandleRequest(context.Request);
                    string responseString = "<HTML><BODY><p>Test</br>Test new line</p></BODY></HTML>";
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    context.Response.ContentLength64 = buffer.Length;
                    Stream output = context.Response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                    listener.Stop();
                }

通过连接到 http://localhost:24578/ 我可以看到我的网站运行良好,如您在此处看到的那样

但是,我想从连接到我网络的其他设备访问我的网站,所以我打开 cmd 并输入 ipconfig,我的本地 ipv4 地址是 192.168.1.108。所以我在浏览器中打开http://192.168.1.108:24578/。它应该可以正常工作,因为它与 localhost 相同,但它向我显示错误 400 错误请求,如此处所示

此外,Web 服务器不会接收到请求,因为它没有在控制台中写入任何内容(HandleRequest 方法会写入有关请求的信息,并且永远不会被调用)。

标签: c#.nethttp

解决方案


您明确表示网络服务器只接受来自本地主机的连接。改变这个

listener.Prefixes.Add("http://localhost:24578/");

listener.Prefixes.Add("http://*:24578/");

您可能需要以管理员权限运行您的应用程序。


推荐阅读