WebApiService.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using LocalhostMES.Core;
  2. using Microsoft.Owin.Hosting;
  3. using System;
  4. using System.Configuration;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace LocalhostMES.Api.Hosting
  8. {
  9. /// <summary>
  10. /// 自托管 Web API(OWIN + Web API 2),供产线/上位机调用。
  11. /// </summary>
  12. public class WebApiService : IDisposable
  13. {
  14. private IDisposable _webApp;
  15. private readonly CancellationTokenSource _cts = new CancellationTokenSource();
  16. private StartOptions _startOptions;
  17. private string _baseUrl = "192.168.1.26:8081";
  18. public void Init(int port = 8081)
  19. {
  20. string url1=ConfigurationManager.AppSettings[ "WebApiUrl" ];
  21. string url2= ConfigurationManager.AppSettings[ "WebApiMesUrl" ];
  22. _baseUrl = $"{url1}:{port}";
  23. _startOptions = new StartOptions
  24. {
  25. Urls = { $"{url1}:{port}", $"{url2}:{port}" }
  26. };
  27. }
  28. public void InitLocalhost(int port = 8081)
  29. {
  30. string url1=ConfigurationManager.AppSettings[ "WebApiUrl" ];
  31. string url2= ConfigurationManager.AppSettings[ "WebApiMesUrl" ];
  32. _baseUrl = $"{url1}:{port}";
  33. _startOptions = new StartOptions
  34. {
  35. Urls = { $"{url1}:{port}"}
  36. };
  37. }
  38. public Task StartAsync()
  39. {
  40. try
  41. {
  42. _webApp = WebApp.Start(_startOptions, app => new OwinWebApiStartup().Configuration(app));
  43. InitializeTestData();
  44. LogHelper.WriteLogInfo($"Web API服务已启动: {_baseUrl}");
  45. Console.WriteLine($"Web API服务已启动: {_baseUrl}");
  46. }
  47. catch (Exception ex)
  48. {
  49. Console.WriteLine($"启动Web API服务失败: {ex.Message}");
  50. LogHelper.WriteLogInfo($"启动Web API服务失败: {ex.Message}");
  51. throw;
  52. }
  53. return Task.CompletedTask;
  54. }
  55. private static void InitializeTestData()
  56. {
  57. try
  58. {
  59. Console.WriteLine("测试数据初始化完成");
  60. }
  61. catch (Exception ex)
  62. {
  63. Console.WriteLine($"初始化测试数据失败: {ex.Message}");
  64. }
  65. }
  66. public Task StopAsync()
  67. {
  68. _webApp?.Dispose();
  69. _webApp = null;
  70. Console.WriteLine("Web API服务已停止");
  71. return Task.CompletedTask;
  72. }
  73. public void Dispose()
  74. {
  75. _cts?.Cancel();
  76. _cts?.Dispose();
  77. _webApp?.Dispose();
  78. GC.SuppressFinalize(this);
  79. }
  80. public bool IsRunning => _webApp != null;
  81. public string BaseUrl => _baseUrl;
  82. }
  83. }