RestService.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. srvcobj = WebApp.Start<Startup>(baseUrl);
  15. MessageBox.Show($"江科HIS读卡服务已成功启动。\n服务地址: {baseUrl}", "服务启动成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
  16. }
  17. catch (Exception ex)
  18. {
  19. // 检查是否是端口占用问题
  20. if (ex.Message.Contains("8321") || ex.Message.Contains("微信") || ex.Message.Contains("冲突"))
  21. {
  22. var result = MessageBox.Show(
  23. $"端口8321被占用(可能是微信等程序)!\n\n" +
  24. $"错误信息: {ex.Message}\n\n" +
  25. $"解决方案:\n" +
  26. $"1. 关闭微信等占用端口的程序\n" +
  27. $"2. 以管理员身份运行本程序\n" +
  28. $"3. 重启计算机释放端口\n\n" +
  29. $"是否打开端口检查工具?",
  30. "端口占用冲突",
  31. MessageBoxButtons.YesNo,
  32. MessageBoxIcon.Warning);
  33. if (result == DialogResult.Yes)
  34. {
  35. try
  36. {
  37. System.Diagnostics.Process.Start("check_port.bat");
  38. }
  39. catch
  40. {
  41. MessageBox.Show("无法启动端口检查工具,请手动运行 check_port.bat", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  42. }
  43. }
  44. }
  45. else
  46. {
  47. MessageBox.Show($"读卡服务启动失败!\n\n错误信息: {ex.Message}\n\n建议解决方案:\n1. 检查端口8321是否被占用\n2. 以管理员身份运行程序\n3. 检查防火墙设置", "服务启动失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
  48. }
  49. throw;
  50. }
  51. }
  52. public void Stop()
  53. {
  54. if (srvcobj != null)
  55. srvcobj.Dispose();
  56. }
  57. }
  58. }