Program.cs 23 KB

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