Program.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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.Hub.Hubs;
  12. using OASystem.API.OAMethodLib.JuHeAPI;
  13. using OASystem.API.OAMethodLib.Logging;
  14. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  15. using OASystem.API.OAMethodLib.Quartz.Jobs;
  16. using OASystem.API.OAMethodLib.SignalR.HubService;
  17. using Quartz;
  18. using Quartz.Impl;
  19. using Quartz.Spi;
  20. using QuzrtzJob.Factory;
  21. using Serilog.Events;
  22. using System.Diagnostics;
  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. };
  186. //SQL报错
  187. db.Aop.OnError = (exp) =>
  188. {
  189. //获取原生SQL推荐 5.1.4.63 性能OK
  190. //UtilMethods.GetNativeSql(exp.sql, exp.parameters);
  191. //获取无参数SQL对性能有影响,特别大的SQL参数多的,调试使用
  192. //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
  193. };
  194. //修改SQL和参数的值
  195. db.Aop.OnExecutingChangeSql = (sql, pars) =>
  196. {
  197. //sql=newsql
  198. //foreach(var p in pars) //修改
  199. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  200. };
  201. }
  202. );
  203. });
  204. #endregion
  205. //#region Identity 配置
  206. //builder.Services.AddDataProtection();
  207. ////不要用 AddIdentity , AddIdentity 是于MVC框架中的
  208. //builder.Services.AddIdentityCore<User>(opt =>
  209. //{
  210. // opt.Password.RequireDigit = false; //数字
  211. // opt.Password.RequireLowercase = false;//小写字母
  212. // opt.Password.RequireNonAlphanumeric = false;//特殊符号 例如 ¥#@!
  213. // opt.Password.RequireUppercase = false; //大写字母
  214. // opt.Password.RequiredLength = 6;//密码长度 6
  215. // opt.Password.RequiredUniqueChars = 1;//相同字符可以出现几次
  216. // opt.Lockout.MaxFailedAccessAttempts = 5; //允许最多输入五次用户名/密码错误
  217. // opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 5, 0);//锁定五分钟
  218. // opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; // 修改密码使用邮件【验证码模式】
  219. // opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; ////
  220. //});
  221. //var idBuilder = new IdentityBuilder(typeof(User), typeof(UserRole), services);
  222. //idBuilder.AddEntityFrameworkStores<swapDbContext>().AddDefaultTokenProviders().AddRoleManager<RoleManager<UserRole>>().AddUserManager<UserManager<User>>();
  223. //#endregion
  224. #region 注入Swagger注释(启用)
  225. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  226. {
  227. builder.Services.AddSwaggerGen(a =>
  228. {
  229. a.SwaggerDoc("v1", new OpenApiInfo
  230. {
  231. Version = "v1",
  232. Title = "Api",
  233. Description = "Api接口文档"
  234. });
  235. foreach (var item in groups)
  236. {
  237. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  238. }
  239. a.DocumentFilter<SwaggerApi>();
  240. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  241. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  242. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  243. {
  244. Description = "Value: Bearer {token}",
  245. Name = "Authorization",
  246. In = ParameterLocation.Header,
  247. Type = SecuritySchemeType.ApiKey,
  248. Scheme = "Bearer"
  249. });
  250. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  251. {{
  252. new OpenApiSecurityScheme
  253. {
  254. Reference = new OpenApiReference
  255. {
  256. Type = ReferenceType.SecurityScheme,
  257. Id = "Bearer"
  258. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  259. }
  260. });
  261. });
  262. }
  263. #endregion
  264. #region 添加校验
  265. builder.Services.AddTransient<OASystemAuthentication>();
  266. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  267. .AddJwtBearer(options =>
  268. {
  269. options.TokenValidationParameters = new TokenValidationParameters
  270. {
  271. ValidateIssuer = true,
  272. ValidateAudience = true,
  273. ValidateLifetime = true,
  274. ValidateIssuerSigningKey = true,
  275. ValidAudience = "OASystem.com",
  276. ValidIssuer = "OASystem.com",
  277. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  278. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  279. RequireExpirationTime = true,
  280. };
  281. options.Events = new JwtBearerEvents
  282. {
  283. OnMessageReceived = context =>
  284. {
  285. var path = context.HttpContext.Request.Path;
  286. //如果是signalr请求,需要将token转存,否则JWT获取不到token。OPTIONS请求需要过滤到,因为OPTIONS请求获取不到Token,用NGINX过滤掉OPTION请求.
  287. if (path.StartsWithSegments("/ChatHub"))
  288. {
  289. string accessToken = context.Request.Query["access_token"].ToString();
  290. if (string.IsNullOrWhiteSpace(accessToken))
  291. {
  292. accessToken = context.Request.Headers["Authorization"].ToString();
  293. }
  294. context.Token = accessToken.Replace("Bearer ", "").Trim();
  295. }
  296. return Task.CompletedTask;
  297. }
  298. };
  299. });
  300. #endregion
  301. #region 初始化日志
  302. var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  303. Log.Logger = new LoggerConfiguration()
  304. //不记录定时访问API
  305. .Filter.ByIncludingOnly(logEvent =>
  306. {
  307. if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
  308. {
  309. var path = pathValue.ToString().Trim('"');
  310. return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
  311. }
  312. return true;
  313. })
  314. .MinimumLevel.Information()
  315. .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  316. .MinimumLevel.Override("System", LogEventLevel.Warning)
  317. .Enrich.FromLogContext()
  318. .WriteTo.Console()
  319. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  320. .CreateLogger();
  321. // 创建出入境费用明细日志记录器专门用于文本记录
  322. // 指定磁盘绝对路径(示例:D盘的AppLogs文件夹)
  323. var logDirectory = @"D:\OASystem\Logs\EnterExitCost";
  324. // 自动创建目录(如果不存在)
  325. try
  326. {
  327. Directory.CreateDirectory(logDirectory);
  328. Log.Information($"日志目录已创建/确认存在: {logDirectory}");
  329. }
  330. catch (Exception ex)
  331. {
  332. Log.Fatal($"无法创建日志目录 {logDirectory}: {ex.Message}");
  333. throw;
  334. }
  335. var eec_TextLogger = new LoggerConfiguration()
  336. .MinimumLevel.Information()
  337. .WriteTo.File(Path.Combine(logDirectory, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  338. .CreateLogger();
  339. // 配置Serilog为Log;
  340. builder.Host.UseSerilog();
  341. builder.Services.AddSingleton<ITextFileLogger>(new TextFileLogger(eec_TextLogger));
  342. #endregion
  343. #region 引入注册Autofac Module
  344. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  345. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  346. {
  347. try
  348. {
  349. builder.RegisterModule(new AutofacRegister());
  350. }
  351. catch (Exception ex)
  352. {
  353. throw new Exception(ex.Message + "\n" + ex.InnerException);
  354. }
  355. });
  356. #endregion
  357. #region AutoMapper
  358. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  359. {
  360. cfg.AddProfile<_baseMappingProfile>();
  361. });
  362. builder.Services.AddSingleton(config);
  363. builder.Services.AddScoped<IMapper, Mapper>();
  364. #endregion
  365. #region DeepSeek AI 服务
  366. // 配置HTTP客户端
  367. builder.Services.AddHttpClient<IDeepSeekService, DeepSeekService>();
  368. #endregion
  369. #region 聚合API 服务
  370. builder.Services.AddControllersWithViews();
  371. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  372. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  373. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  374. #endregion
  375. #region 企业微信API 服务
  376. builder.Services.AddControllersWithViews();
  377. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  378. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  379. #endregion
  380. #region 有道API 服务
  381. //builder.Services.AddControllersWithViews();
  382. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  383. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  384. #endregion
  385. #region 高德地图API 服务
  386. builder.Services.AddHttpClient<GeocodeService>();
  387. #endregion
  388. #region Quartz
  389. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  390. builder.Services.AddSingleton<QuartzFactory>();
  391. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  392. builder.Services.AddSingleton<TaskJob>();
  393. builder.Services.AddSingleton<TaskNewsFeedJob>();
  394. //# new business
  395. builder.Services.AddControllersWithViews();
  396. builder.Services.AddSingleton<IAPNsService, APNsService>();
  397. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  398. #endregion
  399. #region SignalR
  400. builder.Services.AddSignalR()
  401. .AddJsonProtocol(options =>
  402. {
  403. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  404. });
  405. builder.Services.TryAddSingleton(typeof(CommonService));
  406. #endregion
  407. var app = builder.Build();
  408. //自定义异常中间件
  409. app.UseMiddleware<ExceptionHandlingMiddleware>();
  410. //serilog日志 请求中间管道
  411. app.UseSerilogRequestLogging(options =>
  412. {
  413. //options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}, Referer: {Referer}) - {StatusCode} in {Elapsed} ms";
  414. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  415. // 自定义日志级别
  416. options.GetLevel = (httpContext, elapsed, ex) =>
  417. {
  418. if (ex != null) return LogEventLevel.Error;
  419. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  420. // 对健康检查等端点使用更低级别
  421. if (httpContext.Request.Path.StartsWithSegments("/health"))
  422. return LogEventLevel.Debug;
  423. return LogEventLevel.Information;
  424. };
  425. // 丰富日志上下文
  426. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  427. {
  428. // 获取客户端IP(处理代理情况)
  429. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  430. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  431. // 添加IP和其他有用信息到日志上下文
  432. diagnosticContext.Set("ClientIP", ipAddress);
  433. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  434. diagnosticContext.Set("UserAgent", userAgent);
  435. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  436. // 对于API请求添加额外信息
  437. if (httpContext.Request.Path.StartsWithSegments("/api"))
  438. {
  439. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  440. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  441. }
  442. };
  443. });
  444. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  445. // Configure the HTTP request pipeline.
  446. if (!app.Environment.IsDevelopment())
  447. {
  448. app.UseExceptionHandler("/Home/Error");
  449. }
  450. app.UseStaticFiles();
  451. app.UseRouting();
  452. app.UseCors("Cors"); //Cors
  453. //app.UseMiddleware<FixedPromptMiddleware>();
  454. // 定义允许API的访问时间段
  455. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  456. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  457. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  458. //指定API操作记录信息
  459. app.UseMiddleware<RecordAPIOperationMiddleware>();
  460. app.UseAuthentication(); // 认证
  461. app.UseAuthorization(); // 授权
  462. app.UseWhen(context =>
  463. context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
  464. branch => branch.UseResponseCompression());
  465. // 授权路径
  466. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  467. #region 启用swaggerUI
  468. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  469. {
  470. app.UseSwagger();
  471. app.UseSwaggerUI(c =>
  472. {
  473. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  474. foreach (var item in groups)
  475. {
  476. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  477. }
  478. c.RoutePrefix = string.Empty;
  479. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  480. c.DefaultModelsExpandDepth(-1);
  481. //c.EnableFilter();// 添加搜索功能
  482. //c.EnableDeepLinking(); // 启用深度链接
  483. });
  484. }
  485. #endregion
  486. #region Quartz
  487. //获取容器中的QuartzFactory
  488. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  489. app.Lifetime.ApplicationStarted.Register(async () =>
  490. {
  491. await quartz.Start();
  492. });
  493. app.Lifetime.ApplicationStopped.Register(() =>
  494. {
  495. //Quzrtz关闭方法
  496. //quartz.Stop();
  497. });
  498. #endregion
  499. #region SignalR
  500. app.MapHub<ChatHub>("/ChatHub", options =>
  501. {
  502. options.Transports =
  503. HttpTransportType.WebSockets |
  504. HttpTransportType.LongPolling;
  505. });
  506. #endregion
  507. app.MapControllerRoute(
  508. name: "default",
  509. pattern: "{controller=Home}/{action=Index}/{id?}");
  510. app.Run();