Program.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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.Hub.Hubs;
  15. using OASystem.API.OAMethodLib.HunYuanAPI;
  16. using OASystem.API.OAMethodLib.JuHeAPI;
  17. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  18. using OASystem.API.OAMethodLib.Quartz.Jobs;
  19. using OASystem.API.OAMethodLib.SignalR.HubService;
  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 TencentCloud.Common;
  28. using TencentCloud.Common.Profile;
  29. using TencentCloud.Hunyuan.V20230901;
  30. using static OASystem.API.Middlewares.RateLimitMiddleware;
  31. Console.Title = $"FMGJ OASystem Server";
  32. var builder = WebApplication.CreateBuilder(args);
  33. var basePath = AppContext.BaseDirectory;
  34. //引入配置文件
  35. var _config = new ConfigurationBuilder()
  36. .SetBasePath(basePath)
  37. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  38. .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
  39. .AddEnvironmentVariables()
  40. .Build();
  41. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  42. //设置请求参数可不填
  43. builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  44. //设置请求参数错误默认返回格式
  45. builder.Services.AddControllers()
  46. .ConfigureApiBehaviorOptions(options =>
  47. {
  48. options.InvalidModelStateResponseFactory = context =>
  49. {
  50. var errors = context.ModelState
  51. .Where(e => e.Value.Errors.Count > 0)
  52. .ToDictionary(
  53. kvp => kvp.Key,
  54. kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
  55. );
  56. var result = new JsonView
  57. {
  58. Code = 400,
  59. Msg = errors.FirstOrDefault().Value.FirstOrDefault() ?? "",
  60. Data = errors
  61. };
  62. return new BadRequestObjectResult(result);
  63. };
  64. });
  65. // Add services to the container.
  66. builder.Services.AddControllersWithViews();
  67. builder.Services.AddControllers()
  68. .AddJsonOptions(options =>
  69. {
  70. //空字段不响应Response
  71. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  72. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  73. //时间格式化响应
  74. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  75. //decimal 四位小数
  76. //options.JsonSerializerOptions.Converters.Add(new DecimalConverter(_decimalPlaces)); // 将保留小数位数参数传递给自定义序列化器
  77. });
  78. builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  79. #region 添加限流中间件服务注册
  80. // 添加内存缓存(限流需要)
  81. builder.Services.AddMemoryCache();
  82. // 配置限流设置
  83. builder.Services.Configure<RateLimitConfig>(
  84. builder.Configuration.GetSection("RateLimiting"));
  85. #endregion
  86. #region Gzip
  87. builder.Services.AddResponseCompression(options =>
  88. {
  89. options.EnableForHttps = true;
  90. options.Providers.Add<GzipCompressionProvider>();
  91. });
  92. builder.Services.Configure<GzipCompressionProviderOptions>(options =>
  93. {
  94. options.Level = CompressionLevel.Optimal;
  95. });
  96. #endregion
  97. #region Cors
  98. builder.Services.AddCors(options =>
  99. {
  100. //policy.AddPolicy("Cors", opt => opt
  101. // //.SetIsOriginAllowed(origin =>
  102. // //{
  103. // // // 定义允许的来源列表
  104. // // var allowedOrigins = new List<string>
  105. // // {
  106. // // "http://132.232.92.186:9002",
  107. // // "http://oa.pan-american-intl.com:4399"
  108. // // };
  109. // // // 检查请求的来源是否在允许的列表中
  110. // // return allowedOrigins.Contains(origin);
  111. // //})
  112. // //.AllowAnyOrigin()
  113. // //.AllowAnyHeader()
  114. // //.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
  115. // //.AllowCredentials());
  116. // .AllowAnyHeader()
  117. // .AllowAnyMethod()
  118. // .AllowCredentials());
  119. options.AddPolicy("Cors", policy =>
  120. {
  121. policy.AllowAnyOrigin()
  122. .AllowAnyHeader()
  123. .AllowAnyMethod();
  124. });
  125. });
  126. #endregion
  127. #region 上传文件
  128. builder.Services.AddCors(policy =>
  129. {
  130. policy.AddPolicy("Cors", opt => opt
  131. .AllowAnyOrigin()
  132. .AllowAnyHeader()
  133. .AllowAnyMethod()
  134. .WithExposedHeaders("X-Pagination"));
  135. });
  136. builder.Services.Configure<FormOptions>(options =>
  137. {
  138. options.KeyLengthLimit = int.MaxValue;
  139. options.ValueLengthLimit = int.MaxValue;
  140. options.MultipartBodyLengthLimit = int.MaxValue;
  141. options.MultipartHeadersLengthLimit = int.MaxValue;
  142. });
  143. builder.Services.Configure<KestrelServerOptions>(options =>
  144. {
  145. options.Limits.MaxRequestBodySize = int.MaxValue;
  146. options.Limits.MaxRequestBufferSize = int.MaxValue;
  147. });
  148. #endregion
  149. #region 接口分组
  150. var groups = new List<Tuple<string, string>>
  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. //SQL执行前
  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. //sql=newsql
  207. //foreach(var p in pars) //修改
  208. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  209. };
  210. }
  211. );
  212. });
  213. #endregion
  214. #endregion
  215. //#region Identity 配置
  216. //builder.Services.AddDataProtection();
  217. ////不要用 AddIdentity , AddIdentity 是于MVC框架中的
  218. //builder.Services.AddIdentityCore<User>(opt =>
  219. //{
  220. // opt.Password.RequireDigit = false; //数字
  221. // opt.Password.RequireLowercase = false;//小写字母
  222. // opt.Password.RequireNonAlphanumeric = false;//特殊符号 例如 ¥#@!
  223. // opt.Password.RequireUppercase = false; //大写字母
  224. // opt.Password.RequiredLength = 6;//密码长度 6
  225. // opt.Password.RequiredUniqueChars = 1;//相同字符可以出现几次
  226. // opt.Lockout.MaxFailedAccessAttempts = 5; //允许最多输入五次用户名/密码错误
  227. // opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 5, 0);//锁定五分钟
  228. // opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; // 修改密码使用邮件【验证码模式】
  229. // opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; ////
  230. //});
  231. //var idBuilder = new IdentityBuilder(typeof(User), typeof(UserRole), services);
  232. //idBuilder.AddEntityFrameworkStores<swapDbContext>().AddDefaultTokenProviders().AddRoleManager<RoleManager<UserRole>>().AddUserManager<UserManager<User>>();
  233. //#endregion
  234. #region 注入Swagger注释(启用)
  235. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  236. {
  237. builder.Services.AddSwaggerGen(a =>
  238. {
  239. a.SwaggerDoc("v1", new OpenApiInfo
  240. {
  241. Version = "v1",
  242. Title = "Api",
  243. Description = "Api接口文档"
  244. });
  245. foreach (var item in groups)
  246. {
  247. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  248. }
  249. a.DocumentFilter<SwaggerApi>();
  250. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  251. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  252. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  253. {
  254. Description = "Value: Bearer {token}",
  255. Name = "Authorization",
  256. In = ParameterLocation.Header,
  257. Type = SecuritySchemeType.ApiKey,
  258. Scheme = "Bearer"
  259. });
  260. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  261. {{
  262. new OpenApiSecurityScheme
  263. {
  264. Reference = new OpenApiReference
  265. {
  266. Type = ReferenceType.SecurityScheme,
  267. Id = "Bearer"
  268. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  269. }
  270. });
  271. });
  272. }
  273. #endregion
  274. #region 添加校验
  275. builder.Services.AddTransient<OASystemAuthentication>();
  276. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  277. .AddJwtBearer(options =>
  278. {
  279. options.TokenValidationParameters = new TokenValidationParameters
  280. {
  281. ValidateIssuer = true,
  282. ValidateAudience = true,
  283. ValidateLifetime = true,
  284. ValidateIssuerSigningKey = true,
  285. ValidAudience = "OASystem.com",
  286. ValidIssuer = "OASystem.com",
  287. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  288. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  289. RequireExpirationTime = true,
  290. };
  291. options.Events = new JwtBearerEvents
  292. {
  293. OnMessageReceived = context =>
  294. {
  295. var path = context.HttpContext.Request.Path;
  296. //如果是signalr请求,需要将token转存,否则JWT获取不到token。OPTIONS请求需要过滤到,因为OPTIONS请求获取不到Token,用NGINX过滤掉OPTION请求.
  297. if (path.StartsWithSegments("/ChatHub"))
  298. {
  299. string accessToken = context.Request.Query["access_token"].ToString();
  300. if (string.IsNullOrWhiteSpace(accessToken))
  301. {
  302. accessToken = context.Request.Headers["Authorization"].ToString();
  303. }
  304. context.Token = accessToken.Replace("Bearer ", "").Trim();
  305. }
  306. return Task.CompletedTask;
  307. }
  308. };
  309. });
  310. #endregion
  311. #region 初始化日志
  312. var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  313. Log.Logger = new LoggerConfiguration()
  314. //不记录定时访问API
  315. .Filter.ByIncludingOnly(logEvent =>
  316. {
  317. if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
  318. {
  319. var path = pathValue.ToString().Trim('"');
  320. return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
  321. }
  322. return true;
  323. })
  324. .MinimumLevel.Information()
  325. .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  326. .MinimumLevel.Override("System", LogEventLevel.Warning)
  327. .Enrich.FromLogContext()
  328. .WriteTo.Console()
  329. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  330. .CreateLogger();
  331. //
  332. #region 出入境费用明细 专用记录器
  333. // 指定磁盘绝对路径(示例:D盘的AppLogs文件夹)
  334. var logDirectory = @"D:\OASystem\Logs\EnterExitCost";
  335. // 自动创建目录(如果不存在)
  336. try
  337. {
  338. Directory.CreateDirectory(logDirectory);
  339. Log.Information($"日志目录已创建/确认存在: {logDirectory}");
  340. }
  341. catch (Exception ex)
  342. {
  343. Log.Fatal($"无法创建日志目录 {logDirectory}: {ex.Message}");
  344. throw;
  345. }
  346. var eec_TextLogger = new LoggerConfiguration()
  347. .MinimumLevel.Information()
  348. .WriteTo.File(Path.Combine(logDirectory, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  349. .CreateLogger();
  350. #endregion
  351. #region 团组步骤操作 专用记录器
  352. // 指定磁盘绝对路径(示例:D盘的AppLogs文件夹)
  353. var groupLogDir = @"D:\OASystem\Logs\GroupStepOP";
  354. // 自动创建目录(如果不存在)
  355. try
  356. {
  357. Directory.CreateDirectory(groupLogDir);
  358. Log.Information($"日志目录已创建/确认存在: {groupLogDir}");
  359. }
  360. catch (Exception ex)
  361. {
  362. Log.Fatal($"无法创建日志目录 {groupLogDir}: {ex.Message}");
  363. throw;
  364. }
  365. var groupStepOP_TextLogger = new LoggerConfiguration()
  366. .MinimumLevel.Information()
  367. .WriteTo.File(Path.Combine(groupLogDir, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  368. .CreateLogger();
  369. #endregion
  370. #region 任务分配操作 专用记录器
  371. // 指定磁盘绝对路径(示例:D盘的AppLogs文件夹)
  372. var taskLogDir = @"D:\OASystem\Logs\TaskAllocation";
  373. // 自动创建目录(如果不存在)
  374. try
  375. {
  376. Directory.CreateDirectory(taskLogDir);
  377. Log.Information($"日志目录已创建/确认存在: {taskLogDir}");
  378. }
  379. catch (Exception ex)
  380. {
  381. Log.Fatal($"无法创建日志目录 {taskLogDir}: {ex.Message}");
  382. throw;
  383. }
  384. var task_TextLogger = new LoggerConfiguration()
  385. .MinimumLevel.Information()
  386. .WriteTo.File(Path.Combine(taskLogDir, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  387. .CreateLogger();
  388. #endregion
  389. // 配置Serilog为Log;
  390. builder.Host.UseSerilog();
  391. builder.Services.AddSingleton<ITextFileLogger>(new TextFileLogger(eec_TextLogger));
  392. builder.Services.AddSingleton<IGroupTextFileLogger>(new GroupTextFileLogger(groupStepOP_TextLogger));
  393. builder.Services.AddSingleton<ITaskTextFileLogger>(new TaskTextFileLogger(task_TextLogger));
  394. #endregion
  395. #region 引入注册Autofac Module
  396. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  397. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  398. {
  399. try
  400. {
  401. builder.RegisterModule(new AutofacRegister());
  402. }
  403. catch (Exception ex)
  404. {
  405. throw new Exception(ex.Message + "\n" + ex.InnerException);
  406. }
  407. });
  408. #endregion
  409. #region AutoMapper
  410. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  411. {
  412. cfg.AddProfile<_baseMappingProfile>();
  413. });
  414. builder.Services.AddSingleton(config);
  415. builder.Services.AddScoped<IMapper, Mapper>();
  416. #endregion
  417. #region DeepSeek AI 服务
  418. // 配置HTTP客户端
  419. builder.Services.AddHttpClient<IDeepSeekService, DeepSeekService>();
  420. #endregion
  421. #region Doubao API 服务
  422. var doubaoSetting = builder.Configuration.GetSection("DouBao").Get<OASystem.API.OAMethodLib.DoubaoAPI.DoubaoSetting>();
  423. builder.Services.AddSingleton(doubaoSetting);
  424. builder.Services.AddHttpClient("Doubao", c => c.BaseAddress = new Uri(doubaoSetting.BaseAddress));
  425. builder.Services.AddScoped<OASystem.API.OAMethodLib.DoubaoAPI.IDoubaoService, OASystem.API.OAMethodLib.DoubaoAPI.DoubaoService>();
  426. #endregion
  427. #region 聚合API 服务
  428. builder.Services.AddControllersWithViews();
  429. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  430. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  431. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  432. #endregion
  433. #region 企业微信API 服务
  434. builder.Services.AddControllersWithViews();
  435. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  436. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  437. #endregion
  438. #region 混元API
  439. // 从配置中读取腾讯云密钥信息(请确保appsettings.json中有对应配置)
  440. var secretId = builder.Configuration["TencentCloud:SecretId"];
  441. var secretKey = builder.Configuration["TencentCloud:SecretKey"];
  442. var region = builder.Configuration["TencentCloud:Region"] ?? "ap-guangzhou";
  443. // 配置HttpClientFactory(SDK内部会用到)
  444. builder.Services.AddHttpClient();
  445. // 注册腾讯云Hunyuan Client为Singleton(推荐)
  446. builder.Services.AddSingleton(provider =>
  447. {
  448. Credential cred = new Credential
  449. {
  450. SecretId = secretId,
  451. SecretKey = secretKey
  452. };
  453. ClientProfile clientProfile = new ClientProfile();
  454. HttpProfile httpProfile = new HttpProfile
  455. {
  456. Endpoint = "hunyuan.tencentcloudapi.com"
  457. };
  458. clientProfile.HttpProfile = httpProfile;
  459. return new HunyuanClient(cred, region, clientProfile);
  460. });
  461. // 注册自定义服务接口及其实现为Scoped生命周期
  462. builder.Services.AddScoped<IHunyuanService, HunyuanService>();
  463. // 注册混元服务
  464. //builder.Services.AddHttpClient<IHunyuanService, HunyuanService>(client =>
  465. //{
  466. // client.BaseAddress = new Uri("https://hunyuan.ap-chengdu.tencentcloudapi.com/");
  467. // client.Timeout = TimeSpan.FromSeconds(60);
  468. //});
  469. //builder.Services.Configure<HunyuanApiSettings>(builder.Configuration.GetSection("HunyuanApiSettings"));
  470. #endregion
  471. #region 有道API 服务
  472. //builder.Services.AddControllersWithViews();
  473. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  474. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  475. #endregion
  476. #region 高德地图API 服务
  477. builder.Services.AddHttpClient<GeocodeService>();
  478. #endregion
  479. #region 通用搜索服务
  480. builder.Services.AddScoped(typeof(DynamicSearchService<>));
  481. #endregion
  482. #region Quartz
  483. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  484. builder.Services.AddSingleton<QuartzFactory>();
  485. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  486. builder.Services.AddSingleton<TaskJob>();
  487. builder.Services.AddSingleton<TaskNewsFeedJob>();
  488. builder.Services.AddSingleton<PerformanceJob>();
  489. builder.Services.AddSingleton<GroupProcessNodeJob>();
  490. builder.Services.AddSingleton<WeeklyFridayJob>();
  491. //# new business
  492. builder.Services.AddControllersWithViews();
  493. builder.Services.AddSingleton<IAPNsService, APNsService>();
  494. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  495. #endregion
  496. #region SignalR
  497. builder.Services.AddSignalR()
  498. .AddJsonProtocol(options =>
  499. {
  500. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  501. });
  502. builder.Services.TryAddSingleton(typeof(CommonService));
  503. #endregion
  504. var app = builder.Build();
  505. //// 1. 异常处理器应该在最早的位置(除了日志等)
  506. //app.UseExceptionHandler(new ExceptionHandlerOptions
  507. //{
  508. // ExceptionHandlingPath = "/Home/Error",
  509. // AllowStatusCode404Response = true
  510. //});
  511. //自定义异常中间件
  512. //app.UseMiddleware<ExceptionHandlingMiddleware>();
  513. //serilog日志 请求中间管道
  514. app.UseSerilogRequestLogging(options =>
  515. {
  516. //options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}, Referer: {Referer}) - {StatusCode} in {Elapsed} ms";
  517. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  518. // 自定义日志级别
  519. options.GetLevel = (httpContext, elapsed, ex) =>
  520. {
  521. if (ex != null) return LogEventLevel.Error;
  522. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  523. // 对健康检查等端点使用更低级别
  524. if (httpContext.Request.Path.StartsWithSegments("/health"))
  525. return LogEventLevel.Debug;
  526. return LogEventLevel.Information;
  527. };
  528. // 丰富日志上下文
  529. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  530. {
  531. // 获取客户端IP(处理代理情况)
  532. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  533. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  534. // 添加IP和其他有用信息到日志上下文
  535. diagnosticContext.Set("ClientIP", ipAddress);
  536. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  537. diagnosticContext.Set("UserAgent", userAgent);
  538. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  539. // 对于API请求添加额外信息
  540. if (httpContext.Request.Path.StartsWithSegments("/api"))
  541. {
  542. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  543. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  544. }
  545. };
  546. });
  547. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  548. // Configure the HTTP request pipeline.
  549. if (!app.Environment.IsDevelopment())
  550. {
  551. app.UseExceptionHandler("/Home/Error");
  552. }
  553. app.UseStaticFiles();
  554. app.UseRouting();
  555. app.UseCors("Cors"); //Cors
  556. //app.UseMiddleware<FixedPromptMiddleware>();
  557. // 定义允许API的访问时间段
  558. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  559. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  560. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  561. //指定API操作记录信息
  562. app.UseMiddleware<RecordAPIOperationMiddleware>();
  563. app.UseAuthentication(); // 认证
  564. app.UseMiddleware<RateLimitMiddleware>();
  565. app.UseAuthorization(); // 授权
  566. app.UseWhen(context =>
  567. context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
  568. branch => branch.UseResponseCompression());
  569. // 授权路径
  570. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  571. #region 启用swaggerUI
  572. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  573. {
  574. app.UseSwagger();
  575. app.UseSwaggerUI(c =>
  576. {
  577. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  578. foreach (var item in groups)
  579. {
  580. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  581. }
  582. c.RoutePrefix = string.Empty;
  583. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  584. c.DefaultModelsExpandDepth(-1);
  585. //c.EnableFilter();// 添加搜索功能
  586. //c.EnableDeepLinking(); // 启用深度链接
  587. });
  588. }
  589. #endregion
  590. #region Quartz
  591. //获取容器中的QuartzFactory
  592. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  593. app.Lifetime.ApplicationStarted.Register(async () =>
  594. {
  595. await quartz.Start();
  596. });
  597. app.Lifetime.ApplicationStopped.Register(() =>
  598. {
  599. //Quzrtz关闭方法
  600. //quartz.Stop();
  601. });
  602. #endregion
  603. #region SignalR
  604. app.MapHub<ChatHub>("/ChatHub", options =>
  605. {
  606. options.Transports =
  607. HttpTransportType.WebSockets |
  608. HttpTransportType.LongPolling;
  609. });
  610. #endregion
  611. app.MapControllerRoute(
  612. name: "default",
  613. pattern: "{controller=Home}/{action=Index}/{id?}");
  614. app.Run();