Program.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. using Microsoft.AspNetCore.Http.Connections;
  2. using Microsoft.AspNetCore.Http.Features;
  3. using Microsoft.AspNetCore.ResponseCompression;
  4. using Microsoft.AspNetCore.Server.Kestrel.Core;
  5. using Microsoft.Extensions.DependencyInjection.Extensions;
  6. using OASystem.API.Middlewares;
  7. using OASystem.API.OAMethodLib;
  8. using OASystem.API.OAMethodLib.AMapApi;
  9. using OASystem.API.OAMethodLib.APNs;
  10. using OASystem.API.OAMethodLib.DeepSeekAPI;
  11. using OASystem.API.OAMethodLib.GenericSearch;
  12. using OASystem.API.OAMethodLib.Hotmail;
  13. using OASystem.API.OAMethodLib.Hub.Hubs;
  14. using OASystem.API.OAMethodLib.JuHeAPI;
  15. using OASystem.API.OAMethodLib.MicrosoftGraphMailbox;
  16. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  17. using OASystem.API.OAMethodLib.Quartz.Jobs;
  18. using OASystem.API.OAMethodLib.SnovioAPI;
  19. using OASystem.API.OAMethodLib.SignalR.HubService;
  20. using OASystem.API.OAMethodLib.TokenHubAI;
  21. using OASystem.Infrastructure.Logging;
  22. using Quartz;
  23. using Quartz.Impl;
  24. using Quartz.Spi;
  25. using QuzrtzJob.Factory;
  26. using Serilog.Events;
  27. using System.IO.Compression;
  28. using static OASystem.API.Middlewares.RateLimitMiddleware;
  29. Console.Title = $"FMGJ OASystem Server";
  30. var builder = WebApplication.CreateBuilder(args);
  31. var basePath = AppContext.BaseDirectory;
  32. // 导入配置文件
  33. var _config = new ConfigurationBuilder()
  34. .SetBasePath(basePath)
  35. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  36. .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
  37. .AddEnvironmentVariables()
  38. .Build();
  39. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  40. // 设置请求参数发生异常
  41. builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  42. // 设置请求参数错误 默认返回格式
  43. builder.Services.AddControllers()
  44. .ConfigureApiBehaviorOptions(options =>
  45. {
  46. options.InvalidModelStateResponseFactory = context =>
  47. {
  48. var errors = context.ModelState
  49. .Where(e => e.Value.Errors.Count > 0)
  50. .ToDictionary(
  51. kvp => kvp.Key,
  52. kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
  53. );
  54. var result = new JsonView
  55. {
  56. Code = 400,
  57. Msg = errors.FirstOrDefault().Value.FirstOrDefault() ?? "",
  58. Data = errors
  59. };
  60. return new BadRequestObjectResult(result);
  61. };
  62. });
  63. // Add services to the container.
  64. builder.Services.AddControllersWithViews();
  65. builder.Services.AddControllers()
  66. .AddJsonOptions(options =>
  67. {
  68. // 空字段不响应 Response
  69. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  70. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  71. // 时间格式化响应
  72. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  73. // decimal 四位小数
  74. // 保留小数位数参数传递给自定义序列化器
  75. //options.JsonSerializerOptions.Converters.Add(new DecimalConverter(_decimalPlaces));
  76. });
  77. builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  78. #region 添加限流中间件服务注册
  79. // 添加内存缓存,限流中间件使用
  80. builder.Services.AddMemoryCache();
  81. // 配置限流设置
  82. builder.Services.Configure<RateLimitConfig>(
  83. builder.Configuration.GetSection("RateLimiting"));
  84. #endregion
  85. #region Gzip
  86. builder.Services.AddResponseCompression(options =>
  87. {
  88. options.EnableForHttps = true;
  89. options.Providers.Add<GzipCompressionProvider>();
  90. });
  91. builder.Services.Configure<GzipCompressionProviderOptions>(options =>
  92. {
  93. options.Level = CompressionLevel.Optimal;
  94. });
  95. #endregion
  96. #region Cors
  97. builder.Services.AddCors(options =>
  98. {
  99. //policy.AddPolicy("Cors", opt => opt
  100. // //.SetIsOriginAllowed(origin =>
  101. // //{
  102. // // // 定义允许的来源列表
  103. // // var allowedOrigins = new List<string>
  104. // // {
  105. // // "http://132.232.92.186:9002",
  106. // // "http://oa.pan-american-intl.com:4399"
  107. // // };
  108. // // // 检查请求的来源是否在允许的列表中
  109. // // return allowedOrigins.Contains(origin);
  110. // //})
  111. // //.AllowAnyOrigin()
  112. // //.AllowAnyHeader()
  113. // //.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
  114. // //.AllowCredentials());
  115. // .AllowAnyHeader()
  116. // .AllowAnyMethod()
  117. // .AllowCredentials());
  118. options.AddPolicy("Cors", policy =>
  119. {
  120. policy.AllowAnyOrigin()
  121. .AllowAnyHeader()
  122. .AllowAnyMethod();
  123. });
  124. });
  125. #endregion
  126. #region 上传文件
  127. builder.Services.AddCors(policy =>
  128. {
  129. policy.AddPolicy("Cors", opt => opt
  130. .AllowAnyOrigin()
  131. .AllowAnyHeader()
  132. .AllowAnyMethod()
  133. .WithExposedHeaders("X-Pagination"));
  134. });
  135. builder.Services.Configure<FormOptions>(options =>
  136. {
  137. options.KeyLengthLimit = int.MaxValue;
  138. options.ValueLengthLimit = int.MaxValue;
  139. options.MultipartBodyLengthLimit = int.MaxValue;
  140. options.MultipartHeadersLengthLimit = int.MaxValue;
  141. });
  142. builder.Services.Configure<KestrelServerOptions>(options =>
  143. {
  144. options.Limits.MaxRequestBodySize = int.MaxValue;
  145. options.Limits.MaxRequestBufferSize = int.MaxValue;
  146. });
  147. #endregion
  148. #region 上传文件
  149. // 上传文件分组配置:Tuple<分组标识, 分组名称>
  150. var groups = new List<Tuple<string, string>>
  151. {
  152. // 示例分组(取消注释即可启用)
  153. //new Tuple<string, string>("Group1","分组一"),
  154. //new Tuple<string, string>("Group2","分组二")
  155. };
  156. #endregion
  157. #region 接口分组
  158. #region old
  159. builder.Services.AddScoped(options =>
  160. {
  161. return new SqlSugarClient(new List<ConnectionConfig>()
  162. {
  163. new() {
  164. ConfigId = DBEnum.OA2023DB,
  165. ConnectionString = _config.GetConnectionString("OA2023DB"),
  166. DbType = DbType.SqlServer,
  167. IsAutoCloseConnection = true,
  168. },
  169. new()
  170. {
  171. ConfigId = DBEnum.OA2014DB,
  172. ConnectionString = _config.GetConnectionString("OA2014DB"),
  173. DbType = DbType.SqlServer,
  174. IsAutoCloseConnection = true },
  175. }
  176. , db =>
  177. {
  178. // SQL 执行完
  179. db.Aop.OnLogExecuted = (sql, pars) =>
  180. {
  181. // 超过 1 秒
  182. if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
  183. {
  184. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  185. // 执行完成可以输出 SQL 执行时间 (OnLogExecutedDelegate)
  186. Console.WriteLine("NowTime:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
  187. Console.WriteLine("MethodName:" + FirstMethodName);
  188. Console.WriteLine("ElapsedTime:" + db.Ado.SqlExecutionTime.ToString());
  189. Console.WriteLine("ExecuteSQL:" + sql);
  190. }
  191. };
  192. //
  193. db.Aop.OnLogExecuting = (sql, pars) =>
  194. {
  195. };
  196. // SQL 执行前
  197. db.Aop.OnError = (exp) =>
  198. {
  199. // 获取原生 SQL 建议 5.1.4.63 性能 OK
  200. //UtilMethods.GetNativeSql(exp.Sql, exp.Parametres);
  201. // 获取无参数 SQL 对性能有影响,特别是大的 SQL 参数多的,调试使用
  202. //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
  203. };
  204. // 修改 SQL 和参数的值
  205. db.Aop.OnExecutingChangeSql = (sql, pars) =>
  206. {
  207. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  208. };
  209. }
  210. );
  211. });
  212. #endregion
  213. #endregion
  214. #region 注入 Swagger 注解 (禁用)
  215. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  216. {
  217. builder.Services.AddSwaggerGen(a =>
  218. {
  219. a.SwaggerDoc("v1", new OpenApiInfo
  220. {
  221. Version = "v1",
  222. Title = "Api",
  223. Description = "Api 接口文档"
  224. });
  225. foreach (var item in groups)
  226. {
  227. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}鎺ュ彛鏂囨。" });
  228. }
  229. a.DocumentFilter<SwaggerApi>();
  230. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  231. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  232. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  233. {
  234. Description = "Value: Bearer {token}",
  235. Name = "Authorization",
  236. In = ParameterLocation.Header,
  237. Type = SecuritySchemeType.ApiKey,
  238. Scheme = "Bearer"
  239. });
  240. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  241. {{
  242. new OpenApiSecurityScheme
  243. {
  244. Reference = new OpenApiReference
  245. {
  246. Type = ReferenceType.SecurityScheme,
  247. Id = "Bearer"
  248. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  249. }
  250. });
  251. });
  252. }
  253. #endregion
  254. #region 添加校验
  255. builder.Services.AddTransient<OASystemAuthentication>();
  256. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  257. .AddJwtBearer(options =>
  258. {
  259. options.TokenValidationParameters = new TokenValidationParameters
  260. {
  261. ValidateIssuer = true,
  262. ValidateAudience = true,
  263. ValidateLifetime = true,
  264. ValidateIssuerSigningKey = true,
  265. ValidAudience = "OASystem.com",
  266. ValidIssuer = "OASystem.com",
  267. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  268. ClockSkew = TimeSpan.FromSeconds(30), // 过期时间默认值,解决服务器时间不同步问题(秒)
  269. RequireExpirationTime = true,
  270. };
  271. options.Events = new JwtBearerEvents
  272. {
  273. OnMessageReceived = context =>
  274. {
  275. var path = context.HttpContext.Request.Path;
  276. // 如果是 signalr 请求,需要将 token 迁移,否则 JWT 获取不到 token。OPTIONS 请求需要过滤到,因为 OPTIONS 请求获取不到 Token,用 NGINX 过滤掉 OPTIONS 请求。
  277. if (path.StartsWithSegments("/ChatHub"))
  278. {
  279. string accessToken = context.Request.Query["access_token"].ToString();
  280. if (string.IsNullOrWhiteSpace(accessToken))
  281. {
  282. accessToken = context.Request.Headers["Authorization"].ToString();
  283. }
  284. context.Token = accessToken.Replace("Bearer ", "").Trim();
  285. }
  286. return Task.CompletedTask;
  287. }
  288. };
  289. });
  290. #endregion
  291. #region 初始化日志
  292. var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  293. Log.Logger = new LoggerConfiguration()
  294. // 不记录定时访问API
  295. .Filter.ByIncludingOnly(logEvent =>
  296. {
  297. if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
  298. {
  299. var path = pathValue.ToString().Trim('"');
  300. return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
  301. }
  302. return true;
  303. })
  304. .MinimumLevel.Information()
  305. .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  306. .MinimumLevel.Override("System", LogEventLevel.Warning)
  307. .Enrich.FromLogContext()
  308. .WriteTo.Console()
  309. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  310. .CreateLogger();
  311. #region 出入境费用明细 专用记录器
  312. // 出入境费用明细 专用记录器
  313. var logDirectory = @"D:\OASystem\Logs\EnterExitCost";
  314. // 自动创建目录(如果不存在)
  315. try
  316. {
  317. Directory.CreateDirectory(logDirectory);
  318. Log.Information($"日志目录已创建/确认存在: {logDirectory}");
  319. }
  320. catch (Exception ex)
  321. {
  322. Log.Fatal($"无法创建日志目录{logDirectory}: {ex.Message}");
  323. throw;
  324. }
  325. var eec_TextLogger = new LoggerConfiguration()
  326. .MinimumLevel.Information()
  327. .WriteTo.File(Path.Combine(logDirectory, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  328. .CreateLogger();
  329. #endregion
  330. #region 分组步骤操作 专用记录器
  331. // 指定磁盘绝对路径(示例:D盘的AppLogs文件夹)
  332. var groupLogDir = @"D:\OASystem\Logs\GroupStepOP";
  333. // 自动创建目录(如果不存在)
  334. try
  335. {
  336. // 创建目录,若已存在则不执行任何操作
  337. Directory.CreateDirectory(groupLogDir);
  338. // 记录日志:目录已创建/确认存在
  339. Log.Information($"日志目录已创建/确认存在: {groupLogDir}");
  340. }
  341. catch (Exception ex)
  342. {
  343. // 记录致命错误:无法创建日志目录
  344. Log.Fatal($"无法创建日志目录 {groupLogDir}: {ex.Message}");
  345. // 抛出异常终止程序
  346. throw;
  347. }
  348. // 初始化分组步骤操作专用日志器
  349. var groupStepOP_TextLogger = new LoggerConfiguration()
  350. .MinimumLevel.Information() // 最低日志级别:Information
  351. .WriteTo.File( // 输出到文件
  352. Path.Combine(groupLogDir, "text-records-.txt"), // 日志文件路径+名称
  353. rollingInterval: RollingInterval.Month) // 滚动规则:按月生成新文件
  354. .CreateLogger(); // 创建日志实例
  355. #endregion
  356. #region 任务分配操作 专用记录器
  357. // 指定磁盘绝对路径(示例:D盘的AppLogs文件夹)
  358. var taskLogDir = @"D:\OASystem\Logs\TaskAllocation";
  359. // 自动创建目录(如果不存在)
  360. try
  361. {
  362. Directory.CreateDirectory(taskLogDir);
  363. Log.Information($"日志目录已创建/确认存在: {taskLogDir}");
  364. }
  365. catch (Exception ex)
  366. {
  367. Log.Fatal($"无法创建日志目录 {taskLogDir}: {ex.Message}");
  368. throw;
  369. }
  370. // 创建任务分配专用日志实例(按月滚动归档)
  371. var task_TextLogger = new LoggerConfiguration()
  372. .MinimumLevel.Information()
  373. .WriteTo.File(
  374. Path.Combine(taskLogDir, "text-records-.txt"),
  375. rollingInterval: RollingInterval.Month
  376. )
  377. .CreateLogger();
  378. #endregion
  379. // 閰嶇疆Serilog涓篖og;
  380. builder.Host.UseSerilog();
  381. builder.Services.AddSingleton<ITextFileLogger>(new TextFileLogger(eec_TextLogger));
  382. builder.Services.AddSingleton<IGroupTextFileLogger>(new GroupTextFileLogger(groupStepOP_TextLogger));
  383. builder.Services.AddSingleton<ITaskTextFileLogger>(new TaskTextFileLogger(task_TextLogger));
  384. #endregion
  385. #region 注入注册 Autofac 模块
  386. // 使用 Autofac 作为 DI 容器工厂,替换默认容器
  387. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  388. // 配置 Autofac 容器注册
  389. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  390. {
  391. try
  392. {
  393. // 注册自定义 Autofac 注册模块(批量注入服务)
  394. builder.RegisterModule(new AutofacRegister());
  395. }
  396. catch (Exception ex)
  397. {
  398. // 捕获注册异常,拼接异常信息与内部异常,便于排查错误
  399. throw new Exception(ex.Message + "\n" + ex.InnerException);
  400. }
  401. });
  402. #endregion
  403. #region AutoMapper
  404. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  405. {
  406. cfg.AddProfile<_baseMappingProfile>();
  407. });
  408. builder.Services.AddSingleton(config);
  409. builder.Services.AddScoped<IMapper, Mapper>();
  410. #endregion
  411. #region DeepSeek AI 服务
  412. // 配置HTTP客户端:DeepSeek 为长耗时调用,设置超时时间 10 分钟
  413. builder.Services.AddHttpClient<IDeepSeekService, DeepSeekService>(client =>
  414. client.Timeout = TimeSpan.FromMinutes(10));
  415. #endregion
  416. #region 豆包API服务
  417. var doubaoSetting = builder.Configuration.GetSection("DouBao").Get<OASystem.API.OAMethodLib.DoubaoAPI.DoubaoSetting>();
  418. builder.Services.AddSingleton(doubaoSetting);
  419. builder.Services.AddHttpClient("Doubao", c => c.BaseAddress = new Uri(doubaoSetting.BaseAddress));
  420. builder.Services.AddScoped<OASystem.API.OAMethodLib.DoubaoAPI.IDoubaoService, OASystem.API.OAMethodLib.DoubaoAPI.DoubaoService>();
  421. #endregion
  422. #region 聚合API服务
  423. builder.Services.AddControllersWithViews();
  424. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  425. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  426. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  427. #endregion
  428. #region 企业微信 API 服务
  429. builder.Services.AddControllersWithViews();
  430. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  431. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  432. #endregion
  433. #region 混元API
  434. builder.Services.AddTokenHubService(builder.Configuration);
  435. #endregion
  436. #region Snov.io API 服务
  437. builder.Services.Configure<SnovioOptions>(
  438. builder.Configuration.GetSection(SnovioOptions.SectionName));
  439. builder.Services.AddHttpClient<ISnovioService, SnovioService>();
  440. #endregion
  441. #region 有道 API 服务
  442. //builder.Services.AddControllersWithViews();
  443. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  444. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  445. #endregion
  446. #region 高德地图 API 服务
  447. builder.Services.AddHttpClient<GeocodeService>();
  448. #endregion
  449. #region 通用搜索服务
  450. builder.Services.AddScoped(typeof(DynamicSearchService<>));
  451. #endregion
  452. #region Quartz
  453. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  454. builder.Services.AddSingleton<QuartzFactory>();
  455. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  456. builder.Services.AddSingleton<TaskJob>();
  457. builder.Services.AddSingleton<TaskNewsFeedJob>();
  458. builder.Services.AddSingleton<PerformanceJob>();
  459. builder.Services.AddSingleton<GroupProcessNodeJob>();
  460. builder.Services.AddSingleton<WeeklyFridayJob>();
  461. builder.Services.AddSingleton<ProcessAndNotifySummaryJob>();
  462. //# new business
  463. builder.Services.AddControllersWithViews();
  464. builder.Services.AddSingleton<IAPNsService, APNsService>();
  465. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  466. #endregion
  467. #region SignalR
  468. builder.Services.AddSignalR()
  469. .AddJsonProtocol(options =>
  470. {
  471. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  472. });
  473. builder.Services.TryAddSingleton(typeof(CommonService));
  474. #endregion
  475. #region hotmail
  476. builder.Services.AddScoped<HotmailService>();
  477. #endregion
  478. #region Microsoft Graph 邮件服务
  479. builder.Services.Configure<MicrosoftGraphMailboxOptions>(
  480. builder.Configuration.GetSection(MicrosoftGraphMailboxOptions.SectionName));
  481. builder.Services.AddHttpClient("MicrosoftGraph", c =>
  482. {
  483. c.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/");
  484. c.Timeout = TimeSpan.FromMinutes(2);
  485. });
  486. builder.Services.AddSingleton<IMicrosoftGraphMailboxService, MicrosoftGraphMailboxService>();
  487. #endregion
  488. var app = builder.Build();
  489. // Serilog日志 请求中间件
  490. app.UseSerilogRequestLogging(options =>
  491. {
  492. // 自定义日志输出模板
  493. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  494. // 自定义日志级别
  495. options.GetLevel = (httpContext, elapsed, ex) =>
  496. {
  497. // 存在异常 → 错误级别
  498. if (ex != null) return LogEventLevel.Error;
  499. // 500+ 状态码 → 错误级别
  500. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  501. // 健康检查接口使用更低级别(Debug)
  502. if (httpContext.Request.Path.StartsWithSegments("/health"))
  503. return LogEventLevel.Debug;
  504. // 默认信息级别
  505. return LogEventLevel.Information;
  506. };
  507. // 丰富日志上下文(添加自定义字段)
  508. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  509. {
  510. // 获取客户端IP(处理代理场景)
  511. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  512. // 解析客户端操作系统
  513. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  514. // 添加IP及其他有用信息到日志上下文
  515. diagnosticContext.Set("ClientIP", ipAddress);
  516. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  517. diagnosticContext.Set("UserAgent", userAgent);
  518. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  519. // 对API请求额外添加请求头信息
  520. if (httpContext.Request.Path.StartsWithSegments("/api"))
  521. {
  522. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  523. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  524. }
  525. };
  526. });
  527. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  528. // Configure the HTTP request pipeline.
  529. if (!app.Environment.IsDevelopment())
  530. {
  531. app.UseExceptionHandler("/Home/Error");
  532. }
  533. app.UseStaticFiles();
  534. app.UseRouting();
  535. app.UseCors("Cors"); //Cors
  536. //app.UseMiddleware<FixedPromptMiddleware>();
  537. // 定义允许 API 访问的时间范围
  538. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  539. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  540. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  541. // 指定 API 操作记录信息
  542. app.UseMiddleware<RecordAPIOperationMiddleware>();
  543. app.UseAuthentication(); // 认证授权中间件
  544. app.UseMiddleware<RateLimitMiddleware>();
  545. app.UseAuthorization(); // 授权
  546. app.UseWhen(context =>
  547. context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
  548. branch => branch.UseResponseCompression());
  549. // 授权路由
  550. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  551. #region 启用SwaggerUI
  552. // 从配置读取开关,动态启用Swagger文档
  553. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  554. {
  555. app.UseSwagger();
  556. app.UseSwaggerUI(c =>
  557. {
  558. // 默认接口文档版本
  559. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  560. // 遍历分组配置,动态加载多分组接口文档(上传文件分组)
  561. foreach (var item in groups)
  562. {
  563. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  564. }
  565. // 设置根路径访问Swagger(直接域名打开即文档)
  566. c.RoutePrefix = string.Empty;
  567. // 默认不展开接口列表
  568. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  569. // 隐藏模型结构,界面更简洁
  570. c.DefaultModelsExpandDepth(-1);
  571. // 可选功能(已注释)
  572. //c.EnableFilter(); // 启用搜索功能
  573. //c.EnableDeepLinking(); // 启用深度链接
  574. });
  575. }
  576. #endregion
  577. #region Quartz 定时任务
  578. // 容器中获取 Quartz 工厂实例
  579. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  580. // 应用启动时启动 Quartz 定时任务
  581. app.Lifetime.ApplicationStarted.Register(async () =>
  582. {
  583. await quartz.Start();
  584. });
  585. // 应用停止时优雅关闭 Quartz 定时任务
  586. app.Lifetime.ApplicationStopped.Register(() =>
  587. {
  588. //quartz.Stop();
  589. });
  590. #endregion
  591. #region SignalR
  592. app.MapHub<ChatHub>("/ChatHub", options =>
  593. {
  594. options.Transports =
  595. HttpTransportType.WebSockets |
  596. HttpTransportType.LongPolling;
  597. });
  598. #endregion
  599. app.MapControllerRoute(
  600. name: "default",
  601. pattern: "{controller=Home}/{action=Index}/{id?}");
  602. app.Run();