HtmlToPdf/mvp/HtmlToPdfService.Api/Program.cs
2025-12-11 23:35:52 +08:00

107 lines
2.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using HtmlToPdfService.Core.Options;
using HtmlToPdfService.Core.Pool;
using HtmlToPdfService.Core.Services;
using HtmlToPdfService.Core.Storage;
var builder = WebApplication.CreateBuilder(args);
// 配置日志
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
// 绑定配置选项
builder.Services.Configure<PdfServiceOptions>(
builder.Configuration.GetSection("PdfService"));
// 注册服务
builder.Services.AddSingleton<IBrowserPool, BrowserPool>();
builder.Services.AddSingleton<IFileStorage, LocalFileStorage>();
builder.Services.AddScoped<IPdfService, PuppeteerPdfService>();
builder.Services.AddScoped<IImageService, PuppeteerImageService>();
builder.Services.AddScoped<ICallbackService, CallbackService>();
// 注册 HttpClient Factory用于回调
builder.Services.AddHttpClient("CallbackClient")
.ConfigureHttpClient(client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
});
// 添加控制器
builder.Services.AddControllers();
// 添加 API 文档
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// 添加 CORS
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// 配置 HTTP 请求管道
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "HTML to PDF Service API v1");
});
}
app.UseCors();
app.MapControllers();
// 启动时预热浏览器池
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStarted.Register(async () =>
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("应用程序已启动,开始预热浏览器池...");
try
{
var browserPool = app.Services.GetRequiredService<IBrowserPool>();
await browserPool.WarmUpAsync();
logger.LogInformation("浏览器池预热完成");
}
catch (Exception ex)
{
logger.LogError(ex, "浏览器池预热失败");
}
});
// 优雅关闭
lifetime.ApplicationStopping.Register(async () =>
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("应用程序正在停止,清理资源...");
try
{
var browserPool = app.Services.GetRequiredService<IBrowserPool>();
await browserPool.DisposeAsync();
logger.LogInformation("浏览器池已清理");
}
catch (Exception ex)
{
logger.LogError(ex, "清理浏览器池时出错");
}
});
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("HTML to PDF Service 已启动");
logger.LogInformation("Swagger UI: http://localhost:5000/swagger");
app.Run();