Program.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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 聚合API 服务
  417. builder.Services.AddControllersWithViews();
  418. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  419. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  420. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  421. #endregion
  422. #region 企业微信API 服务
  423. builder.Services.AddControllersWithViews();
  424. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  425. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  426. #endregion
  427. #region 混元API
  428. // 从配置中读取腾讯云密钥信息(请确保appsettings.json中有对应配置)
  429. var secretId = builder.Configuration["TencentCloud:SecretId"];
  430. var secretKey = builder.Configuration["TencentCloud:SecretKey"];
  431. var region = builder.Configuration["TencentCloud:Region"] ?? "ap-guangzhou";
  432. // 配置HttpClientFactory(SDK内部会用到)
  433. builder.Services.AddHttpClient();
  434. // 注册腾讯云Hunyuan Client为Singleton(推荐)
  435. builder.Services.AddSingleton(provider =>
  436. {
  437. Credential cred = new Credential
  438. {
  439. SecretId = secretId,
  440. SecretKey = secretKey
  441. };
  442. ClientProfile clientProfile = new ClientProfile();
  443. HttpProfile httpProfile = new HttpProfile
  444. {
  445. Endpoint = "hunyuan.tencentcloudapi.com"
  446. };
  447. clientProfile.HttpProfile = httpProfile;
  448. return new HunyuanClient(cred, region, clientProfile);
  449. });
  450. // 注册自定义服务接口及其实现为Scoped生命周期
  451. builder.Services.AddScoped<IHunyuanService, HunyuanService>();
  452. // 注册混元服务
  453. //builder.Services.AddHttpClient<IHunyuanService, HunyuanService>(client =>
  454. //{
  455. // client.BaseAddress = new Uri("https://hunyuan.ap-chengdu.tencentcloudapi.com/");
  456. // client.Timeout = TimeSpan.FromSeconds(60);
  457. //});
  458. //builder.Services.Configure<HunyuanApiSettings>(builder.Configuration.GetSection("HunyuanApiSettings"));
  459. #endregion
  460. #region 有道API 服务
  461. //builder.Services.AddControllersWithViews();
  462. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  463. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  464. #endregion
  465. #region 高德地图API 服务
  466. builder.Services.AddHttpClient<GeocodeService>();
  467. #endregion
  468. #region 通用搜索服务
  469. builder.Services.AddScoped(typeof(DynamicSearchService<>));
  470. #endregion
  471. #region Quartz
  472. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  473. builder.Services.AddSingleton<QuartzFactory>();
  474. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  475. builder.Services.AddSingleton<TaskJob>();
  476. builder.Services.AddSingleton<TaskNewsFeedJob>();
  477. builder.Services.AddSingleton<PerformanceJob>();
  478. builder.Services.AddSingleton<GroupProcessNodeJob>();
  479. //# new business
  480. builder.Services.AddControllersWithViews();
  481. builder.Services.AddSingleton<IAPNsService, APNsService>();
  482. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  483. #endregion
  484. #region SignalR
  485. builder.Services.AddSignalR()
  486. .AddJsonProtocol(options =>
  487. {
  488. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  489. });
  490. builder.Services.TryAddSingleton(typeof(CommonService));
  491. #endregion
  492. var app = builder.Build();
  493. //// 1. 异常处理器应该在最早的位置(除了日志等)
  494. //app.UseExceptionHandler(new ExceptionHandlerOptions
  495. //{
  496. // ExceptionHandlingPath = "/Home/Error",
  497. // AllowStatusCode404Response = true
  498. //});
  499. //自定义异常中间件
  500. //app.UseMiddleware<ExceptionHandlingMiddleware>();
  501. //serilog日志 请求中间管道
  502. app.UseSerilogRequestLogging(options =>
  503. {
  504. //options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}, Referer: {Referer}) - {StatusCode} in {Elapsed} ms";
  505. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  506. // 自定义日志级别
  507. options.GetLevel = (httpContext, elapsed, ex) =>
  508. {
  509. if (ex != null) return LogEventLevel.Error;
  510. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  511. // 对健康检查等端点使用更低级别
  512. if (httpContext.Request.Path.StartsWithSegments("/health"))
  513. return LogEventLevel.Debug;
  514. return LogEventLevel.Information;
  515. };
  516. // 丰富日志上下文
  517. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  518. {
  519. // 获取客户端IP(处理代理情况)
  520. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  521. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  522. // 添加IP和其他有用信息到日志上下文
  523. diagnosticContext.Set("ClientIP", ipAddress);
  524. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  525. diagnosticContext.Set("UserAgent", userAgent);
  526. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  527. // 对于API请求添加额外信息
  528. if (httpContext.Request.Path.StartsWithSegments("/api"))
  529. {
  530. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  531. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  532. }
  533. };
  534. });
  535. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  536. // Configure the HTTP request pipeline.
  537. if (!app.Environment.IsDevelopment())
  538. {
  539. app.UseExceptionHandler("/Home/Error");
  540. }
  541. app.UseStaticFiles();
  542. app.UseRouting();
  543. app.UseCors("Cors"); //Cors
  544. //app.UseMiddleware<FixedPromptMiddleware>();
  545. // 定义允许API的访问时间段
  546. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  547. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  548. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  549. //指定API操作记录信息
  550. app.UseMiddleware<RecordAPIOperationMiddleware>();
  551. app.UseAuthentication(); // 认证
  552. app.UseMiddleware<RateLimitMiddleware>();
  553. app.UseAuthorization(); // 授权
  554. app.UseWhen(context =>
  555. context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
  556. branch => branch.UseResponseCompression());
  557. // 授权路径
  558. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  559. #region 启用swaggerUI
  560. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  561. {
  562. app.UseSwagger();
  563. app.UseSwaggerUI(c =>
  564. {
  565. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  566. foreach (var item in groups)
  567. {
  568. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  569. }
  570. c.RoutePrefix = string.Empty;
  571. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  572. c.DefaultModelsExpandDepth(-1);
  573. //c.EnableFilter();// 添加搜索功能
  574. //c.EnableDeepLinking(); // 启用深度链接
  575. });
  576. }
  577. #endregion
  578. #region Quartz
  579. //获取容器中的QuartzFactory
  580. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  581. app.Lifetime.ApplicationStarted.Register(async () =>
  582. {
  583. await quartz.Start();
  584. });
  585. app.Lifetime.ApplicationStopped.Register(() =>
  586. {
  587. //Quzrtz关闭方法
  588. //quartz.Stop();
  589. });
  590. #endregion
  591. #region SignalR
  592. app.MapHub<ChatHub>("/ChatHub", options =>
  593. {
  594. options.Transports =
  595. HttpTransportType.WebSockets |
  596. HttpTransportType.LongPolling;
  597. });
  598. #endregion
  599. app.MapControllerRoute(
  600. name: "default",
  601. pattern: "{controller=Home}/{action=Index}/{id?}");
  602. app.Run();