c# - 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 方法会写入有关请求的信息,并且永远不会被调用)。
解决方案
您明确表示网络服务器只接受来自本地主机的连接。改变这个
listener.Prefixes.Add("http://localhost:24578/");
至
listener.Prefixes.Add("http://*:24578/");
您可能需要以管理员权限运行您的应用程序。
推荐阅读
- excel - 如何重构长循环?
- c++ - Clang-Tidy:冗余的 'operator<<' 声明
- python - 对于大小为 41 的轴 0,索引 41 超出范围
- node.js - 在 Node js 中安装 express 包时,出现错误
- html - 打字稿在检查重复项时,它也考虑了空白
- asp.net-core - 在没有事务的情况下运行 SQL
- module - 如何通过代码使我的自定义模块在应用切换器 odoo12 中可见
- python - 如何使用 python/pandas 从 href 获取 href 链接
- cider - 在 emacs/cider 中打开 leiningen 项目会引发类路径错误
- android - 在用户通过“Ok Google,让我在线”等语音请求后,如何在谷歌助手中显示我的“应用操作”?