Program.cs 24 KB

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