WebApiService.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. using LocalhostMES.Core;
  2. using LocalhostMES.DataBase;
  3. using Microsoft.Owin.Hosting;
  4. using Org.BouncyCastle.Asn1.Ocsp;
  5. using Owin;
  6. using Prism.Ioc;
  7. using System;
  8. using System.Net;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Web.Http;
  12. using Unity;
  13. using Unity.Lifetime;
  14. using Unity.WebApi;
  15. namespace LocalhostMES.Controller
  16. {
  17. public class WebApiService : IDisposable
  18. {
  19. private IDisposable _webApp;
  20. private CancellationTokenSource _cts = new CancellationTokenSource();
  21. private int _port;
  22. private StartOptions _startOptions;
  23. private string _baseUrl="192.168.1.26:8081";
  24. public WebApiService()
  25. {
  26. }
  27. public void Init(int port = 8081)
  28. {
  29. _port = port;
  30. _baseUrl = $"http://192.168.1.26:{port}";
  31. _startOptions = new StartOptions { Urls = { $"http://192.168.1.26:{port}",$"http://10.157.15.51:{port}" } };//",
  32. }
  33. public async Task StartAsync()
  34. {
  35. try
  36. {
  37. // 创建 Startup 实例并传入容器提供者
  38. var startup = new Startup();
  39. // 启动 Web App
  40. _webApp = WebApp.Start(_startOptions, startup.Configuration);
  41. // 启动Web API服务
  42. // 初始化测试数据
  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. }
  54. private void InitializeTestData()
  55. {
  56. try
  57. {
  58. //// 添加一些测试工单
  59. //var testWorkOrder = new Models.WorkOrderInfo
  60. //{
  61. // WorkOrderNo = "GD-001",
  62. // MaterialCode = "T03GCD",
  63. // MaterialName = "T03贯穿灯",
  64. // PlannedQuantity = 100,
  65. // CompletedQuantity = 0,
  66. // Status = "2", // 已发布
  67. // LineCode = "RSC01",
  68. // CreateTime = DateTime.Now.AddDays(-1),
  69. // StartTime = DateTime.Now.AddHours(-2),
  70. // EndTime = DateTime.Now.AddHours(1),
  71. //};
  72. //DatabaseHelper.InsertWorkOrderInfo(testWorkOrder);
  73. //// 生成测试SN
  74. //for ( int i = 1; i <= 10; i++ )
  75. //{
  76. // DatabaseHelper.InsertSnInfo(new Models.SnInfo
  77. // {
  78. // Sn = $"P-T03GCD-{DateTime.Now:yyMMddHHmm}-{i:D4}-{Guid.NewGuid().ToString("N").Substring(0, 6).ToUpper()}",
  79. // GenerateTime = DateTime.Now.AddMinutes(-i * 5),
  80. // WorkOrderNo = "GD-001",
  81. // PrintType = "产品码",
  82. // IsUsed = i > 5 // 前5个已使用
  83. // });
  84. //}
  85. Console.WriteLine("测试数据初始化完成");
  86. }
  87. catch ( Exception ex )
  88. {
  89. Console.WriteLine($"初始化测试数据失败: {ex.Message}");
  90. }
  91. }
  92. public Task StopAsync()
  93. {
  94. _webApp?.Dispose();
  95. _webApp = null;
  96. Console.WriteLine("Web API服务已停止");
  97. return Task.CompletedTask;
  98. }
  99. public void Dispose()
  100. {
  101. _cts?.Cancel();
  102. _cts?.Dispose();
  103. _webApp?.Dispose();
  104. GC.SuppressFinalize(this);
  105. }
  106. public bool IsRunning => _webApp != null;
  107. public string BaseUrl => _baseUrl;
  108. }
  109. // OWIN Startup类
  110. public class Startup
  111. {
  112. public void Configuration(IAppBuilder app)
  113. {
  114. // 创建 Unity 容器
  115. var container = new UnityContainer();
  116. // 启用CORS
  117. app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  118. // 配置Web API
  119. var config = new HttpConfiguration();
  120. // 启用属性路由
  121. config.MapHttpAttributeRoutes();
  122. // 配置默认路由
  123. config.Routes.MapHttpRoute(
  124. name: "DefaultApi",
  125. routeTemplate: "api/{controller}/{action}/{id}",
  126. defaults: new { id = RouteParameter.Optional }
  127. );
  128. config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
  129. Newtonsoft.Json.ReferenceLoopHandling.Ignore;
  130. config.Formatters.JsonFormatter.SerializerSettings.Formatting =
  131. Newtonsoft.Json.Formatting.Indented;
  132. // 使用Web API
  133. app.UseWebApi(config);
  134. }
  135. }
  136. // 辅助类,用于跨控制器共享数据
  137. //public static class ConcurrentStorage
  138. //{
  139. // //public static readonly System.Collections.Concurrent.ConcurrentDictionary<string, Models.WorkOrderInfo> WorkOrders
  140. // // = new System.Collections.Concurrent.ConcurrentDictionary<string, Models.WorkOrderInfo>();
  141. // //public static readonly System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Generic.List<Models.SnInfo>> WorkOrderSns
  142. // // = new System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Generic.List<Models.SnInfo>>();
  143. // //public static readonly System.Collections.Concurrent.ConcurrentBag<Models.BindRecord> BindRecords
  144. // // = new System.Collections.Concurrent.ConcurrentBag<Models.BindRecord>();
  145. // //public static readonly System.Collections.Concurrent.ConcurrentBag<Models.ProcessRecord> ProcessRecords
  146. // // = new System.Collections.Concurrent.ConcurrentBag<Models.ProcessRecord>();
  147. //}
  148. }