Technology Sharing

C# implements HTTPS listening service embedded in exe and upgrades from HTTP to HTTPS backend windows service

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Since the customer needs to upgrade the original HTTP backend service to a service that supports https, and because the original HTTP service is implemented based on the HTTP listening service embedded in the WINDOWS service, it does not support https, and does not directly load the HTTPS certificate like other WebAPI services deployed in IIS, so here it is necessary to modify the original service to support https and perform HTTPS port binding settings on the server environment, as follows:

(Note: The following operations require that you already have an HTTPS certificate.)

1. Install the certificate, double-click the pfx file and install it to:Local Computer”–>“personal”;

2. Double-click to opencrtCertificate, you can see the fingerprint information (certhash) in the detailed information;

3. Execute port binding (default port 443)

netsh http add sslcert ipport=0.0.0.0:8080 certhash=指纹 appid={程序GUID/newguid} clientcertnegotiation=enable

4. Server program implementation:

  1. using System;
  2. public class HttpService
  3. {
  4. public MyHttpServer()
  5. {
  6. System.Net.HttpListener httpListener = new System.Net.HttpListener();
  7. httpListener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;
  8. httpListener.Prefixes.Add("https://*:8000/"); // 支持https
  9. httpListener.Start();
  10. new System.Threading.Thread(new System.Threading.ThreadStart(delegate
  11. {
  12. while (true)
  13. {
  14. try
  15. {
  16. System.Net.HttpListenerContext httpListenerContext = httpListener.GetContext();
  17. new System.Threading.Thread(new System.Threading.ParameterizedThreadStart((input) =>
  18. {
  19. System.Net.HttpListenerContext ctx = (System.Net.HttpListenerContext)input;
  20. System.Net.HttpListenerRequest request = ctx.Request;
  21. string pram = request.QueryString["Data"];//Get入参
  22. string responseMessage = string.Empty;//返回值
  23. if (!string.IsNullOrEmpty(pram))
  24. {
  25. //Get入参
  26. pramOrg = pram;
  27. pram = System.Web.HttpUtility.UrlDecode(pram);
  28. }
  29. //POST入参
  30. if (request.HttpMethod == "POST")
  31. {
  32. //处理业务请求
  33. StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8);
  34. pram = reader.ReadToEnd();
  35. reader.Close();
  36. reader.Dispose();
  37. }
  38. #region 业务处理
  39. try
  40. {
  41. //业务处理
  42. responseMessage = "业务结果";
  43. }
  44. catch (Exception ex)
  45. {
  46. //异常处理
  47. responseMessage = ex.Message;
  48. }
  49. #endregion 业务处理
  50. #region 返回给调用者
  51. //输出类型
  52. httpListenerContext.Response.ContentType = "text/html; charset=UTF-8";
  53. //返回状态
  54. httpListenerContext.Response.StatusCode = 200;
  55. //设置授权,尝试解决Jquery跨域问题
  56. //httpListenerContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
  57. //httpListenerContext.Response.Headers["Access-Control-Allow-Methods"] = "GET,POST";
  58. //httpListenerContext.Response.Headers["Access-Control-Max-Age"] = "1000";
  59. try
  60. {
  61. //输出界面内容
  62. if (!string.IsNullOrEmpty(responseMessage))
  63. {
  64. //返回文本内容
  65. using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))
  66. {
  67. writer.Write(responseMessage);
  68. }
  69. }
  70. }
  71. catch
  72. {
  73. //刷新太快异常,不做处理
  74. }
  75. #endregion 返回给调用者
  76. })).Start(httpListenerContext);
  77. }
  78. catch
  79. { }
  80. }
  81. })).Start();
  82. }
  83. }

If an error occurs during the port binding process, or the addition fails, refer to the following steps:

1. Check whether the parameters of the netsh command are correct;

2. SSL certificate addition failed, error: 1312 The specified login session does not exist. It may have been terminated. Solution:

Press WIN+R on the keyboard and enter mmc.exe, as follows:

    

Click 'OK', and the following console root node interface will pop up.

Select File->Add/Remove Snap-in, or directly press ctrl+m to pop up the following window and perform the operation:

Then go to Personal to import the certificate

Finally, bind the SSL certificate to the port number

netsh http add sslcert ipport=0.0.0.0:8080 certhash=指纹 appid={程序GUID/newguid} clientcertnegotiation=enable