Program.cs 23 KB

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