refactor:规范代码格式和注释

This commit is contained in:
ShaoHua
2026-04-06 22:59:16 +08:00
parent 758f6772c6
commit d00a907da0
34 changed files with 1095 additions and 200 deletions
@@ -13,19 +13,41 @@ using AppSettings = Hua.Todo.Maui.Models.AppSettings;
namespace Hua.Todo.Maui.Services;
/// <summary>
/// Windows 平台嵌入式 Web 服务器实现
/// 使用 ASP.NET Core 运行
/// </summary>
public class EmbeddedWebServerService : IEmbeddedWebServerService
{
private WebApplication? _webApp;
private readonly AppSettings _appSettings;
/// <summary>
/// 服务器是否正在运行
/// </summary>
public bool IsRunning => _webApp != null;
/// <summary>
/// 服务器基础 URL
/// </summary>
public string BaseUrl => _appSettings.WebServer.HostUrl;
/// <summary>
/// 初始化嵌入式 Web 服务器服务
/// </summary>
/// <param name="appSettings">应用程序配置</param>
public EmbeddedWebServerService(AppSettings appSettings)
{
_appSettings = appSettings;
}
/// <summary>
/// 异步启动服务器。
/// 启动时机:通常在应用启动或用户手动开启服务时调用。
/// 错误处理:启动失败会抛出 ASP.NET Core 相关异常,建议在调用方进行 catch 处理。
/// 线程安全:非 UI 线程相关,可在后台线程调用;方法内部已处理重入(若已运行则直接返回)。
/// </summary>
/// <returns>表示启动操作的任务</returns>
public async Task StartAsync()
{
if (_webApp != null) return;
@@ -34,6 +56,7 @@ public class EmbeddedWebServerService : IEmbeddedWebServerService
builder.WebHost.UseUrls(_appSettings.WebServer.HostUrl);
// 配置控制器和 JSON 选项
builder.Services.AddControllers()
.AddApplicationPart(typeof(Hua.Todo.Application.ServiceCollectionExtensions).Assembly)
.AddJsonOptions(options =>
@@ -43,9 +66,10 @@ public class EmbeddedWebServerService : IEmbeddedWebServerService
builder.Services.AddEndpointsApiExplorer();
// 注册应用逻辑服务
builder.Services.AddApplicationServices(_appSettings.WebServer.ConnectionString);
// 配置跨域策略
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
@@ -58,6 +82,7 @@ public class EmbeddedWebServerService : IEmbeddedWebServerService
var app = builder.Build();
// 如果配置为使用静态文件(前端托管),则配置静态文件服务
if (_appSettings.WebServer.IsUsingStatic)
{
ServeStaticFiles(app);
@@ -73,6 +98,10 @@ public class EmbeddedWebServerService : IEmbeddedWebServerService
await _webApp.StartAsync();
}
/// <summary>
/// 配置静态文件服务(用于托管 Vue 前端)
/// </summary>
/// <param name="app">Web 应用程序实例</param>
private void ServeStaticFiles(WebApplication app)
{
try
@@ -100,6 +129,7 @@ public class EmbeddedWebServerService : IEmbeddedWebServerService
};
app.UseStaticFiles(staticFileOptions);
// 处理 SPA 路由
app.Use(async (context, next) =>
{
if (context.Request.Path.HasValue)
@@ -125,6 +155,11 @@ public class EmbeddedWebServerService : IEmbeddedWebServerService
}
}
/// <summary>
/// 异步停止服务器。
/// 释放服务器资源并停止监听。
/// </summary>
/// <returns>表示停止操作的任务</returns>
public async Task StopAsync()
{
if (_webApp == null) return;