Program.cs 21 KB

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