How to enable SSL in WebSocket with System.Net.Htt

2019-04-02 18:07发布

问题:

I'm using .Net 4.5 and HttpListener class on Windows Azure(a worker role) to make my own WebSocket server. For HTTP non-secure connections it works very well. The problem is that I need to make WebSocket connection secured with SSL(wss://).

I've seeking around and neither HttpListener class documentation and internet(even here) hasn't helped me so much.

I found that httpcfg.exe should help me configure the certificate but no lucky.

So, that are my questions:

  1. Is there any way to enable it from my code? Like read the certificate from store and set it on HttpListener somehow?
  2. If not, httpcfg.exe is the solution? If yest, how to use it?
  3. If 1 == No and 2 == yes, how can I use httpcfg in Azure?

Thanks! I really appreciate the help...

Best regards...

Gutemberg

回答1:

Ok, just figured out.

Since HttpListener is a wrapper to HTTP.sys, we must configure it before start using HttpListener.

The httpcfg.exe is used on windows versions prior to Windows Vista. Since I'm using .net 4.5 HttpListener WebSockets and it only works on Windows8/windows Server 2012(if you try use websockets on pre-windows8 versions of windows, you will get a PlattaformNotSupportedException), we should use netsh utility instead of httpcfg.

So, to configure HTTP.sys in Windows 8 open CMD and add the following command to it:

netsh http add sslcert ipport=IP:PORT certhash=YOU_CERT_HASH appid={GUID}

Change IP and PORT to the desired IP address and PORT number that you want secure withing your certificate and YOUR_CERT_HASH with the thumbprint of your certificate(the cert should be previous uploaded into azure portal) and GUID with a GUID you generate from any GUID generation tool like the one from Visual Studio(Tools > Create Guid).

After it, you just need to set the HttpListener.Prefix.Add("https://youIP:youPort/yourPath") and you should be good.

Like me, some people will ask how to make it work on Windows Azure... You can use the Startup tasks to run this command before your role is started and setup HTTP.sys as needed.

For more information on how to use startup tasks, check this documentation on MSDN http://msdn.microsoft.com/en-us/library/windowsazure/hh180155.aspx and for more details on httpcfg or netsh, check this other doc in MSDN http://msdn.microsoft.com/en-us/library/ms733791.aspx