detect/detect.gui/Api/ApiService.cs

74 lines
2.2 KiB
C#
Raw Normal View History

2024-11-13 17:09:15 +08:00
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using detect.gui.Api.System;
using detect.gui.Converters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using xwd.utils;
namespace detect.gui.Api;
public class ApiService
{
private static ApiService? _instance;
public static ApiService Instance
{
get
{
_instance = new ApiService();
return _instance;
}
}
private WebApplication? _webApp = null;
public void StartService()
{
if (_webApp != null) return;
var appBuilder = WebApplication.CreateBuilder();
appBuilder.Services.AddRouting();
appBuilder.Services.AddLogging();
// 添加 CORS 服务
appBuilder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// json
appBuilder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); // 可选:支持枚举为字符串
options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // 使用驼峰命名法
options.SerializerOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss")); // 设置日期时间格式
});
_webApp = appBuilder.Build();
// 使用 CORS 中间件
_webApp.UseCors("AllowAll");
// api
_ = new DetectTaskApi(_webApp);
_ = new DeviceApi(_webApp);
_ = new LogApi(_webApp);
_ = new UserApi(_webApp);
_ = new AuthorityApi(_webApp);
Task.Run(() => { _webApp.RunAsync(AppSettingsManager.Manager().GetString("ApiUrl")); });
Log.Information("Web Application is started!");
}
public async void StopService()
{
if (_webApp == null) return;
await _webApp.StopAsync();
_webApp = null;
Log.Information("Web Application is stopped!");
}
}