好吧,如果我运行这个简化的代码片段,程序会剧烈崩溃,甚至不会抛出异常。
所以这是我之前所做的:
- 已创建 ssl 证书
- 绑定(bind)到8443端口
- 通过“httpcfg -list”验证
- 确保“8443.cer”和“8443.pkv”在“user/.config/.mono/httplistener”中
所以一切都应该正常吗?错误的!这让我发疯了好几个小时..
using System;
using System.Net;
using System.Text;
public class HttpListenerTest {
public static void Main(string[] args) {
Console.WriteLine("Initialize..");
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://*:8089/");
listener.Prefixes.Add("https://*:8443/");
listener.Start();
while (true) {
Console.WriteLine("Listening..");
HttpListenerContext context = listener.GetContext();
Console.WriteLine("Respond..");
byte[] bytes = Encoding.UTF8.GetBytes("works!");
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();
context.Response.Close();
}
}
}
如果我运行此代码并在端口 8089 上发出 http 请求,一切都很好。 8443 上的 https 请求终止了进程,唯一发生的事情是“异常事件”( Screenshot here ) 在 Debug模式下。
..用谷歌搜索丢失的文件名,得到 4 个不相关的结果。
我的知识已经用完了,真的需要 ssl 才能与监听器一起工作。
因此,如果您对此有任何经验或建议,请告诉我。
最佳答案
2 这个问题的解决方案:
如果您需要快速修复本地主机(仅针对本地主机)
感谢 SushiHangovers 的评论,将缺少的环境变量“MONO_TLS_PROVIDER”设置为“btls”(BoringSSL)解决了这个问题。
$ MONO_TLS_PROVIDER=btls mono servertest.exe
如果您需要它在服务器上工作
感谢 Gusman,这里有一个简短易懂的指南,介绍如何使用 Nginx 管理 SSL 和向 Mono 服务器发送 Http 请求。
1.首先安装/设置Nginx
www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-16-04
2.然后安装Certbot
certbot.eff.org
3. 使用 Certbot 保护 Nginx
www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04
4. 反向代理到您的 HttpListener 端口 ( taken from here )
4.1打开Nginx配置文件
$ sudo nano /etc/nginx/sites-available/default
4.2 注释掉默认的 try_files 行并指定反向代理设置
. . .
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404;
# Reverse proxy settings
include proxy_params;
proxy_pass http://localhost:8010;
}
. . .
并改变
server_name _;
到
server_name example.com www.example.com;
现在你应该可以开始了。
关于C# HttpListener 在 SSL 上完全失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46289016/