首页 文章

C#HttpListener在SSL上完全失败

提问于
浏览
0

好吧,如果我正在运行这个简化的代码片段,程序会剧烈崩溃,甚至不会抛出异常 .

所以这就是我事先做过的事情:

  • 创建了ssl证书

  • 将其绑定到端口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请求导致进程失败,唯一发生的事情是调试模式下的'unusual event'(Screenshot here) .

..缺少文件名,得到4个不相关的结果 .

我的知识结束了,真的需要ssl与听众合作 .

因此,如果您对此有任何建议或建议,请告诉我 .

1 回答

  • 1

    2此问题的解决方案:

    If you need a quick fix for localhost (Just for localhost)

    感谢SushiHangovers评论,将缺少的环境变量'MONO_TLS_PROVIDER'设置为'btls'(BoringSSL)修复了问题 .

    $ MONO_TLS_PROVIDER=btls mono servertest.exe
    

    If you need it to work on a server

    感谢Gusman,这里有一个简短易懂的指南,介绍如何使用Nginx管理SSL并向HIO请求发送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;
    

    现在你应该好好去 .

相关问题