Program.cs 21 KB

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