| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using LocalhostMES.Core;
- using Microsoft.Owin.Hosting;
- using System;
- using System.Configuration;
- using System.Threading;
- using System.Threading.Tasks;
- namespace LocalhostMES.Api.Hosting
- {
- /// <summary>
- /// 自托管 Web API(OWIN + Web API 2),供产线/上位机调用。
- /// </summary>
- public class WebApiService : IDisposable
- {
- private IDisposable _webApp;
- private readonly CancellationTokenSource _cts = new CancellationTokenSource();
- private StartOptions _startOptions;
- private string _baseUrl = "192.168.1.26:8081";
- public void Init(int port = 8081)
- {
- string url1=ConfigurationManager.AppSettings[ "WebApiUrl" ];
- string url2= ConfigurationManager.AppSettings[ "WebApiMesUrl" ];
- _baseUrl = $"{url1}:{port}";
- _startOptions = new StartOptions
- {
- Urls = { $"{url1}:{port}", $"{url2}:{port}" }
- };
- }
- public void InitLocalhost(int port = 8081)
- {
- string url1=ConfigurationManager.AppSettings[ "WebApiUrl" ];
- string url2= ConfigurationManager.AppSettings[ "WebApiMesUrl" ];
- _baseUrl = $"{url1}:{port}";
- _startOptions = new StartOptions
- {
- Urls = { $"{url1}:{port}"}
- };
- }
- public Task StartAsync()
- {
- try
- {
- _webApp = WebApp.Start(_startOptions, app => new OwinWebApiStartup().Configuration(app));
- InitializeTestData();
- LogHelper.WriteLogInfo($"Web API服务已启动: {_baseUrl}");
- Console.WriteLine($"Web API服务已启动: {_baseUrl}");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"启动Web API服务失败: {ex.Message}");
- LogHelper.WriteLogInfo($"启动Web API服务失败: {ex.Message}");
- throw;
- }
- return Task.CompletedTask;
- }
- private static void InitializeTestData()
- {
- try
- {
- Console.WriteLine("测试数据初始化完成");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"初始化测试数据失败: {ex.Message}");
- }
- }
- public Task StopAsync()
- {
- _webApp?.Dispose();
- _webApp = null;
- Console.WriteLine("Web API服务已停止");
- return Task.CompletedTask;
- }
- public void Dispose()
- {
- _cts?.Cancel();
- _cts?.Dispose();
- _webApp?.Dispose();
- GC.SuppressFinalize(this);
- }
- public bool IsRunning => _webApp != null;
- public string BaseUrl => _baseUrl;
- }
- }
|