Program.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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://119.45.113.139: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. // 表单缓冲超 64KB 后会落盘为临时文件(FileBufferingReadStream.CreateTempFile,
  142. // 默认 C:\WINDOWS\TEMP\ASPNETCORE_*.tmp,IIS 应用池常无写入权限)。
  143. // 阈值设为 int.MaxValue 让表单常驻内存,避免上传稍大文件时报
  144. // Access to the path 'C:\WINDOWS\TEMP\ASPNETCORE_*.tmp' is denied。
  145. // 注意:单文件仍受 MultipartBodyLengthLimit 约束,本处已放开。
  146. options.MemoryBufferThreshold = int.MaxValue;
  147. options.BufferBody = true;
  148. });
  149. builder.Services.Configure<KestrelServerOptions>(options =>
  150. {
  151. options.Limits.MaxRequestBodySize = int.MaxValue;
  152. options.Limits.MaxRequestBufferSize = int.MaxValue;
  153. });
  154. #endregion
  155. #region 上传文件
  156. // 上传文件分组配置:Tuple<分组标识, 分组名称>
  157. var groups = new List<Tuple<string, string>>
  158. {
  159. // 示例分组(取消注释即可启用)
  160. //new Tuple<string, string>("Group1","分组一"),
  161. //new Tuple<string, string>("Group2","分组二")
  162. };
  163. #endregion
  164. #region 接口分组
  165. #region old
  166. builder.Services.AddScoped(options =>
  167. {
  168. return new SqlSugarClient(new List<ConnectionConfig>()
  169. {
  170. new() {
  171. ConfigId = DBEnum.OA2023DB,
  172. ConnectionString = _config.GetConnectionString("OA2023DB"),
  173. DbType = DbType.SqlServer,
  174. IsAutoCloseConnection = true,
  175. },
  176. new()
  177. {
  178. ConfigId = DBEnum.OA2014DB,
  179. ConnectionString = _config.GetConnectionString("OA2014DB"),
  180. DbType = DbType.SqlServer,
  181. IsAutoCloseConnection = true },
  182. }
  183. , db =>
  184. {
  185. // SQL 执行完
  186. db.Aop.OnLogExecuted = (sql, pars) =>
  187. {
  188. // 超过 1 秒
  189. if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
  190. {
  191. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  192. // 执行完成可以输出 SQL 执行时间 (OnLogExecutedDelegate)
  193. Console.WriteLine("NowTime:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
  194. Console.WriteLine("MethodName:" + FirstMethodName);
  195. Console.WriteLine("ElapsedTime:" + db.Ado.SqlExecutionTime.ToString());
  196. Console.WriteLine("ExecuteSQL:" + sql);
  197. }
  198. };
  199. //
  200. db.Aop.OnLogExecuting = (sql, pars) =>
  201. {
  202. };
  203. // SQL 执行前
  204. db.Aop.OnError = (exp) =>
  205. {
  206. // 获取原生 SQL 建议 5.1.4.63 性能 OK
  207. //UtilMethods.GetNativeSql(exp.Sql, exp.Parametres);
  208. // 获取无参数 SQL 对性能有影响,特别是大的 SQL 参数多的,调试使用
  209. //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
  210. };
  211. // 修改 SQL 和参数的值
  212. db.Aop.OnExecutingChangeSql = (sql, pars) =>
  213. {
  214. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  215. };
  216. }
  217. );
  218. });
  219. #endregion
  220. #endregion
  221. #region 注入 Swagger 注解 (禁用)
  222. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  223. {
  224. builder.Services.AddSwaggerGen(a =>
  225. {
  226. a.SwaggerDoc("v1", new OpenApiInfo
  227. {
  228. Version = "v1",
  229. Title = "Api",
  230. Description = "Api 接口文档"
  231. });
  232. foreach (var item in groups)
  233. {
  234. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}鎺ュ彛鏂囨。" });
  235. }
  236. a.DocumentFilter<SwaggerApi>();
  237. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  238. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  239. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  240. {
  241. Description = "Value: Bearer {token}",
  242. Name = "Authorization",
  243. In = ParameterLocation.Header,
  244. Type = SecuritySchemeType.ApiKey,
  245. Scheme = "Bearer"
  246. });
  247. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  248. {{
  249. new OpenApiSecurityScheme
  250. {
  251. Reference = new OpenApiReference
  252. {
  253. Type = ReferenceType.SecurityScheme,
  254. Id = "Bearer"
  255. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  256. }
  257. });
  258. });
  259. }
  260. #endregion
  261. #region 添加校验
  262. builder.Services.AddTransient<OASystemAuthentication>();
  263. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  264. .AddJwtBearer(options =>
  265. {
  266. options.TokenValidationParameters = new TokenValidationParameters
  267. {
  268. ValidateIssuer = true,
  269. ValidateAudience = true,
  270. ValidateLifetime = true,
  271. ValidateIssuerSigningKey = true,
  272. ValidAudience = "OASystem.com",
  273. ValidIssuer = "OASystem.com",
  274. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  275. ClockSkew = TimeSpan.FromSeconds(30), // 过期时间默认值,解决服务器时间不同步问题(秒)
  276. RequireExpirationTime = true,
  277. };
  278. options.Events = new JwtBearerEvents
  279. {
  280. OnMessageReceived = context =>
  281. {
  282. var path = context.HttpContext.Request.Path;
  283. // 如果是 signalr 请求,需要将 token 迁移,否则 JWT 获取不到 token。OPTIONS 请求需要过滤到,因为 OPTIONS 请求获取不到 Token,用 NGINX 过滤掉 OPTIONS 请求。
  284. if (path.StartsWithSegments("/ChatHub"))
  285. {
  286. string accessToken = context.Request.Query["access_token"].ToString();
  287. if (string.IsNullOrWhiteSpace(accessToken))
  288. {
  289. accessToken = context.Request.Headers["Authorization"].ToString();
  290. }
  291. context.Token = accessToken.Replace("Bearer ", "").Trim();
  292. }
  293. return Task.CompletedTask;
  294. }
  295. };
  296. });
  297. #endregion
  298. #region 初始化日志
  299. var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  300. Log.Logger = new LoggerConfiguration()
  301. // 不记录定时访问API
  302. .Filter.ByIncludingOnly(logEvent =>
  303. {
  304. if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
  305. {
  306. var path = pathValue.ToString().Trim('"');
  307. return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
  308. }
  309. return true;
  310. })
  311. .MinimumLevel.Information()
  312. .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  313. .MinimumLevel.Override("System", LogEventLevel.Warning)
  314. .Enrich.FromLogContext()
  315. .WriteTo.Console()
  316. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  317. .CreateLogger();
  318. #region 出入境费用明细 专用记录器
  319. // 出入境费用明细 专用记录器(项目根目录下 Logs/EnterExitCost)
  320. var logDirectory = Path.Combine(basePath, "Logs", "EnterExitCost");
  321. // 自动创建目录(如果不存在)
  322. try
  323. {
  324. Directory.CreateDirectory(logDirectory);
  325. Log.Information($"日志目录已创建/确认存在: {logDirectory}");
  326. }
  327. catch (Exception ex)
  328. {
  329. Log.Fatal($"无法创建日志目录{logDirectory}: {ex.Message}");
  330. throw;
  331. }
  332. var eec_TextLogger = new LoggerConfiguration()
  333. .MinimumLevel.Information()
  334. .WriteTo.File(Path.Combine(logDirectory, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  335. .CreateLogger();
  336. #endregion
  337. #region 分组步骤操作 专用记录器
  338. // 项目根目录下 Logs/GroupStepOP
  339. var groupLogDir = Path.Combine(basePath, "Logs", "GroupStepOP");
  340. // 自动创建目录(如果不存在)
  341. try
  342. {
  343. // 创建目录,若已存在则不执行任何操作
  344. Directory.CreateDirectory(groupLogDir);
  345. // 记录日志:目录已创建/确认存在
  346. Log.Information($"日志目录已创建/确认存在: {groupLogDir}");
  347. }
  348. catch (Exception ex)
  349. {
  350. // 记录致命错误:无法创建日志目录
  351. Log.Fatal($"无法创建日志目录 {groupLogDir}: {ex.Message}");
  352. // 抛出异常终止程序
  353. throw;
  354. }
  355. // 初始化分组步骤操作专用日志器
  356. var groupStepOP_TextLogger = new LoggerConfiguration()
  357. .MinimumLevel.Information() // 最低日志级别:Information
  358. .WriteTo.File( // 输出到文件
  359. Path.Combine(groupLogDir, "text-records-.txt"), // 日志文件路径+名称
  360. rollingInterval: RollingInterval.Month) // 滚动规则:按月生成新文件
  361. .CreateLogger(); // 创建日志实例
  362. #endregion
  363. #region 任务分配操作 专用记录器
  364. // 项目根目录下 Logs/TaskAllocation
  365. var taskLogDir = Path.Combine(basePath, "Logs", "TaskAllocation");
  366. // 自动创建目录(如果不存在)
  367. try
  368. {
  369. Directory.CreateDirectory(taskLogDir);
  370. Log.Information($"日志目录已创建/确认存在: {taskLogDir}");
  371. }
  372. catch (Exception ex)
  373. {
  374. Log.Fatal($"无法创建日志目录 {taskLogDir}: {ex.Message}");
  375. throw;
  376. }
  377. // 创建任务分配专用日志实例(按月滚动归档)
  378. var task_TextLogger = new LoggerConfiguration()
  379. .MinimumLevel.Information()
  380. .WriteTo.File(
  381. Path.Combine(taskLogDir, "text-records-.txt"),
  382. rollingInterval: RollingInterval.Month
  383. )
  384. .CreateLogger();
  385. #endregion
  386. // 閰嶇疆Serilog涓篖og;
  387. builder.Host.UseSerilog();
  388. builder.Services.AddSingleton<ITextFileLogger>(new TextFileLogger(eec_TextLogger));
  389. builder.Services.AddSingleton<IGroupTextFileLogger>(new GroupTextFileLogger(groupStepOP_TextLogger));
  390. builder.Services.AddSingleton<ITaskTextFileLogger>(new TaskTextFileLogger(task_TextLogger));
  391. #endregion
  392. #region 注入注册 Autofac 模块
  393. // 使用 Autofac 作为 DI 容器工厂,替换默认容器
  394. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  395. // 配置 Autofac 容器注册
  396. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  397. {
  398. try
  399. {
  400. // 注册自定义 Autofac 注册模块(批量注入服务)
  401. builder.RegisterModule(new AutofacRegister());
  402. }
  403. catch (Exception ex)
  404. {
  405. // 捕获注册异常,拼接异常信息与内部异常,便于排查错误
  406. throw new Exception(ex.Message + "\n" + ex.InnerException);
  407. }
  408. });
  409. #endregion
  410. #region AutoMapper
  411. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  412. {
  413. cfg.AddProfile<_baseMappingProfile>();
  414. });
  415. builder.Services.AddSingleton(config);
  416. builder.Services.AddScoped<IMapper, Mapper>();
  417. #endregion
  418. #region DeepSeek AI 服务
  419. // 配置HTTP客户端:DeepSeek 为长耗时调用,设置超时时间 10 分钟
  420. builder.Services.AddHttpClient<IDeepSeekService, DeepSeekService>(client =>
  421. client.Timeout = TimeSpan.FromMinutes(10));
  422. #endregion
  423. #region 豆包API服务
  424. var doubaoSetting = builder.Configuration.GetSection("DouBao").Get<OASystem.API.OAMethodLib.DoubaoAPI.DoubaoSetting>();
  425. builder.Services.AddSingleton(doubaoSetting);
  426. builder.Services.AddHttpClient("Doubao", c => c.BaseAddress = new Uri(doubaoSetting.BaseAddress));
  427. builder.Services.AddScoped<OASystem.API.OAMethodLib.DoubaoAPI.IDoubaoService, OASystem.API.OAMethodLib.DoubaoAPI.DoubaoService>();
  428. #endregion
  429. #region 聚合API服务
  430. builder.Services.AddControllersWithViews();
  431. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  432. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  433. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  434. #endregion
  435. #region 企业微信 API 服务
  436. builder.Services.AddControllersWithViews();
  437. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  438. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  439. #endregion
  440. #region 混元API
  441. builder.Services.AddTokenHubService(builder.Configuration);
  442. #endregion
  443. #region Snov.io API 服务
  444. builder.Services.Configure<SnovioOptions>(
  445. builder.Configuration.GetSection(SnovioOptions.SectionName));
  446. builder.Services.AddHttpClient<ISnovioService, SnovioService>();
  447. #endregion
  448. #region 有道 API 服务
  449. //builder.Services.AddControllersWithViews();
  450. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  451. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  452. #endregion
  453. #region 高德地图 API 服务
  454. builder.Services.AddHttpClient<GeocodeService>();
  455. #endregion
  456. #region 通用搜索服务
  457. builder.Services.AddScoped(typeof(DynamicSearchService<>));
  458. #endregion
  459. #region Quartz
  460. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  461. builder.Services.AddSingleton<QuartzFactory>();
  462. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  463. builder.Services.AddSingleton<TaskJob>();
  464. builder.Services.AddSingleton<TaskNewsFeedJob>();
  465. builder.Services.AddSingleton<PerformanceJob>();
  466. builder.Services.AddSingleton<GroupProcessNodeJob>();
  467. builder.Services.AddSingleton<WeeklyFridayJob>();
  468. builder.Services.AddSingleton<ProcessAndNotifySummaryJob>();
  469. //# new business
  470. builder.Services.AddControllersWithViews();
  471. builder.Services.AddSingleton<IAPNsService, APNsService>();
  472. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  473. #endregion
  474. #region SignalR
  475. builder.Services.AddSignalR()
  476. .AddJsonProtocol(options =>
  477. {
  478. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  479. });
  480. builder.Services.TryAddSingleton(typeof(CommonService));
  481. #endregion
  482. #region hotmail
  483. builder.Services.AddScoped<HotmailService>();
  484. #endregion
  485. #region Microsoft Graph 邮件服务
  486. builder.Services.Configure<MicrosoftGraphMailboxOptions>(
  487. builder.Configuration.GetSection(MicrosoftGraphMailboxOptions.SectionName));
  488. builder.Services.AddHttpClient("MicrosoftGraph", c =>
  489. {
  490. c.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/");
  491. c.Timeout = TimeSpan.FromMinutes(2);
  492. });
  493. builder.Services.AddSingleton<IMicrosoftGraphMailboxService, MicrosoftGraphMailboxService>();
  494. #endregion
  495. var app = builder.Build();
  496. // Serilog日志 请求中间件
  497. app.UseSerilogRequestLogging(options =>
  498. {
  499. // 自定义日志输出模板
  500. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  501. // 自定义日志级别
  502. options.GetLevel = (httpContext, elapsed, ex) =>
  503. {
  504. // 存在异常 → 错误级别
  505. if (ex != null) return LogEventLevel.Error;
  506. // 500+ 状态码 → 错误级别
  507. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  508. // 健康检查接口使用更低级别(Debug)
  509. if (httpContext.Request.Path.StartsWithSegments("/health"))
  510. return LogEventLevel.Debug;
  511. // 默认信息级别
  512. return LogEventLevel.Information;
  513. };
  514. // 丰富日志上下文(添加自定义字段)
  515. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  516. {
  517. // 获取客户端IP(处理代理场景)
  518. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  519. // 解析客户端操作系统
  520. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  521. // 添加IP及其他有用信息到日志上下文
  522. diagnosticContext.Set("ClientIP", ipAddress);
  523. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  524. diagnosticContext.Set("UserAgent", userAgent);
  525. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  526. // 对API请求额外添加请求头信息
  527. if (httpContext.Request.Path.StartsWithSegments("/api"))
  528. {
  529. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  530. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  531. }
  532. };
  533. });
  534. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  535. // Configure the HTTP request pipeline.
  536. if (!app.Environment.IsDevelopment())
  537. {
  538. app.UseExceptionHandler("/Home/Error");
  539. }
  540. app.UseStaticFiles();
  541. app.UseRouting();
  542. app.UseCors("Cors"); //Cors
  543. //app.UseMiddleware<FixedPromptMiddleware>();
  544. // 全局异常兜底(放管道最前,异常时尝试回滚当前请求事务;db 取不到仅记日志不影响响应)
  545. app.UseMiddleware<ExceptionHandlingMiddleware>();
  546. // 定义允许 API 访问的时间范围
  547. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  548. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  549. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  550. // 指定 API 操作记录信息
  551. app.UseMiddleware<RecordAPIOperationMiddleware>();
  552. app.UseAuthentication(); // 认证授权中间件
  553. app.UseMiddleware<RateLimitMiddleware>();
  554. app.UseAuthorization(); // 授权
  555. app.UseWhen(context =>
  556. context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
  557. branch => branch.UseResponseCompression());
  558. // 授权路由
  559. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  560. #region 启用SwaggerUI
  561. // 从配置读取开关,动态启用Swagger文档
  562. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  563. {
  564. app.UseSwagger();
  565. app.UseSwaggerUI(c =>
  566. {
  567. // 默认接口文档版本
  568. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  569. // 遍历分组配置,动态加载多分组接口文档(上传文件分组)
  570. foreach (var item in groups)
  571. {
  572. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  573. }
  574. // 设置根路径访问Swagger(直接域名打开即文档)
  575. c.RoutePrefix = string.Empty;
  576. // 默认不展开接口列表
  577. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  578. // 隐藏模型结构,界面更简洁
  579. c.DefaultModelsExpandDepth(-1);
  580. // 可选功能(已注释)
  581. //c.EnableFilter(); // 启用搜索功能
  582. //c.EnableDeepLinking(); // 启用深度链接
  583. });
  584. }
  585. #endregion
  586. #region Quartz 定时任务
  587. // 容器中获取 Quartz 工厂实例
  588. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  589. // 应用启动时启动 Quartz 定时任务
  590. app.Lifetime.ApplicationStarted.Register(async () =>
  591. {
  592. await quartz.Start();
  593. });
  594. // 应用停止时优雅关闭 Quartz 定时任务
  595. app.Lifetime.ApplicationStopped.Register(() =>
  596. {
  597. //quartz.Stop();
  598. });
  599. #endregion
  600. #region SignalR
  601. app.MapHub<ChatHub>("/ChatHub", options =>
  602. {
  603. options.Transports =
  604. HttpTransportType.WebSockets |
  605. HttpTransportType.LongPolling;
  606. });
  607. #endregion
  608. app.MapControllerRoute(
  609. name: "default",
  610. pattern: "{controller=Home}/{action=Index}/{id?}");
  611. app.Run();