using Fake.AspNetCore; using Fake.Autofac; using Fake.Modularity; using Fake.Rbac.Application; using Fake.Rbac.Infrastructure; using Fake.AspNetCore.Auditing; using Fake.AspNetCore.Mvc; using Fake.FeiShu; using Fake.Security.Claims; using Fake.Serilog; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging; using Oms.Application; using Oms.SqlSugarCore; using SimpleAdmin.Api.Auth; namespace SimpleAdmin.Api; [DependsOn( typeof(FakeAutofacModule), typeof(OmsApplicationModule), typeof(OmsSqlSugarCoreModule), typeof(FakeRbacApplicationModule), typeof(FakeRbacInfrastructureModule), typeof(FakeSerilogModule) )] public class SimpleAdminApiModule : FakeModule { private const string DefaultCorsPolicyName = "default"; public override void PreConfigureServices(ServiceConfigurationContext context) { FakeClaimTypes.UserId = "mapId"; } public override void ConfigureServices(ServiceConfigurationContext context) { var services = context.Services; var configuration = context.Services.GetConfiguration(); // 配置动态 API - 扫描 OMS 与 RBAC 应用服务 services.Configure(options => { options.ApplicationServices2Controller(); options.ApplicationServices2Controller(settings => { settings.RootPath = "rbac"; settings.TypePredicate = type => type == typeof(AuthService); }); options.ApplicationServices2Controller(settings => { settings.RootPath = "rbac"; settings.TypePredicate = type => type != typeof(Fake.Rbac.Application.Services.AuthService); }); }); services.AddFakeAspNetCoreAuditing(); // 添加 Fake Swagger 支持 services.AddFakeSwaggerGen(addSecurity: true); services.AddCors(options => { options.AddPolicy(DefaultCorsPolicyName, builder => { builder.WithOrigins(configuration.GetSection("App:CorsOrigins").Get() ?? []) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.Configure(options => { // 反向代理场景下恢复客户端真实来源信息,供 Swagger、鉴权和重定向等中间件使用 options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); } public override void ConfigureApplication(ApplicationConfigureContext context) { var app = context.GetWebApplication(); // 必须在读取 Scheme/Host/PathBase 的中间件之前执行,否则 Swagger 会生成错误的请求地址 app.UseForwardedHeaders(); // 虚拟路由-网关适配 app.UsePathBase(app.Configuration["ASPNETCORE_PATHBASE"]); // Swagger app.UseFakeSwagger(); // 异常处理 app.UseFakeExceptionHandling(); // CORS app.UseCors(DefaultCorsPolicyName); // 静态文件服务(用于头像等上传文件) app.UseStaticFiles(); // 路由 - 必须在认证和授权之前 app.UseRouting(); // 认证和授权 app.UseAuthentication(); app.UseAuthorization(); // 端点映射 app.MapControllers(); var shouldSendStartupNotification = !app.Environment.IsEnvironment("Testing") && app.Configuration.GetValue("App:SendStartupNotification", true); if (!shouldSendStartupNotification) { return; } try { app.Services.GetRequiredService().Send("Application started"); } catch (Exception ex) { app.Logger.LogWarning(ex, "Failed to send startup notification."); } } }