Program.cs 23 KB

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