Program.cs 25 KB

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