RestService.cs 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using Microsoft.Owin.Hosting;
  2. using System;
  3. using System.Windows.Forms;
  4. namespace ThCardReader
  5. {
  6. class RestService
  7. {
  8. private IDisposable srvcobj;
  9. public void Start()
  10. {
  11. string baseUrl = "http://localhost:8321"; // 保持原端口8321
  12. try
  13. {
  14. // 优先尝试同时绑定所有网卡与 localhost,确保既能用 IP 又能用 localhost 访问
  15. var options = new StartOptions();
  16. options.Urls.Add("http://+:8321");
  17. options.Urls.Add(baseUrl);
  18. srvcobj = WebApp.Start<Startup>(options);
  19. MessageBox.Show($"江科HIS读卡服务已成功启动。\n服务地址: http://<本机IP>:8321 / {baseUrl}", "服务启动成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
  20. }
  21. catch (Exception ex)
  22. {
  23. // 检查是否是端口占用问题
  24. if (ex.Message.Contains("8321") || ex.Message.Contains("微信") || ex.Message.Contains("冲突"))
  25. {
  26. var result = MessageBox.Show(
  27. $"端口8321被占用(可能是微信等程序)!\n\n" +
  28. $"错误信息: {ex.Message}\n\n" +
  29. $"解决方案:\n" +
  30. $"1. 关闭微信等占用端口的程序\n" +
  31. $"2. 以管理员身份运行本程序\n" +
  32. $"3. 重启计算机释放端口\n\n" +
  33. $"是否打开端口检查工具?",
  34. "端口占用冲突",
  35. MessageBoxButtons.YesNo,
  36. MessageBoxIcon.Warning);
  37. if (result == DialogResult.Yes)
  38. {
  39. try
  40. {
  41. System.Diagnostics.Process.Start("check_port.bat");
  42. }
  43. catch
  44. {
  45. MessageBox.Show("无法启动端口检查工具,请手动运行 check_port.bat", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  46. }
  47. }
  48. }
  49. else
  50. {
  51. MessageBox.Show($"读卡服务启动失败!\n\n错误信息: {ex.Message}\n\n建议解决方案:\n1. 检查端口8321是否被占用\n2. 以管理员身份运行程序\n3. 检查防火墙设置", "服务启动失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  52. // // 若绑定所有网卡失败(例如缺少URLACL权限),降级仅监听 localhost,保证原有流程可用
  53. // try
  54. // {
  55. // srvcobj = WebApp.Start<Startup>(baseUrl);
  56. // MessageBox.Show($"江科HIS读卡服务已以兼容模式启动(仅本机访问)。\n服务地址: {baseUrl}\n\n如需IP访问,请以管理员运行并执行URLACL与防火墙放行。", "服务启动成功(兼容模式)", MessageBoxButtons.OK, MessageBoxIcon.Information);
  57. // return;
  58. // }
  59. // catch
  60. // {
  61. // MessageBox.Show($"读卡服务启动失败!\n\n错误信息: {ex.Message}\n\n建议解决方案:\n1. 检查端口8321是否被占用\n2. 以管理员身份运行程序\n3. 执行URLACL与防火墙放行", "服务启动失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  62. // }
  63. }
  64. throw;
  65. }
  66. }
  67. public void Stop()
  68. {
  69. if (srvcobj != null)
  70. srvcobj.Dispose();
  71. }
  72. }
  73. }