Program.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. using Microsoft.AspNetCore.Http.Connections;
  2. using Microsoft.AspNetCore.Http.Features;
  3. using Microsoft.AspNetCore.Server.Kestrel.Core;
  4. using Microsoft.Extensions.DependencyInjection.Extensions;
  5. using OASystem.API.Middlewares;
  6. using OASystem.API.OAMethodLib;
  7. using OASystem.API.OAMethodLib.AMapApi;
  8. using OASystem.API.OAMethodLib.APNs;
  9. using OASystem.API.OAMethodLib.Hub.Hubs;
  10. using OASystem.API.OAMethodLib.JuHeAPI;
  11. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  12. using OASystem.API.OAMethodLib.Quartz.Jobs;
  13. using OASystem.API.OAMethodLib.SignalR.HubService;
  14. using Quartz;
  15. using Quartz.Impl;
  16. using Quartz.Spi;
  17. using QuzrtzJob.Factory;
  18. using Serilog.Formatting.Compact;
  19. Console.Title = $"FMGJ OASystem Server";
  20. var builder = WebApplication.CreateBuilder(args);
  21. var basePath = AppContext.BaseDirectory;
  22. //引入配置文件
  23. var _config = new ConfigurationBuilder()
  24. .SetBasePath(basePath)
  25. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  26. .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
  27. .AddEnvironmentVariables()
  28. .Build();
  29. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  30. //设置请求参数可不填
  31. builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  32. // Add services to the container.
  33. builder.Services.AddControllersWithViews();
  34. builder.Services.AddControllers()
  35. .AddJsonOptions(options =>
  36. {
  37. //空字段不响应Response
  38. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  39. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  40. //时间格式化响应
  41. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  42. //decimal 四位小数
  43. //options.JsonSerializerOptions.Converters.Add(new DecimalConverter(_decimalPlaces)); // 将保留小数位数参数传递给自定义序列化器
  44. });
  45. builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  46. #region Cors
  47. builder.Services.AddCors(policy =>
  48. {
  49. //policy.AddPolicy("Cors", opt => opt
  50. //.AllowAnyOrigin()
  51. //.AllowAnyHeader()
  52. //.AllowAnyMethod()
  53. //.WithExposedHeaders("X-Pagination"));
  54. policy.AddPolicy("Cors", opt => opt
  55. .SetIsOriginAllowed(origin =>
  56. {
  57. // 定义允许的来源列表
  58. var allowedOrigins = new List<string>
  59. {
  60. "http://132.232.92.186:9002"
  61. };
  62. // 检查请求的来源是否在允许的列表中
  63. return allowedOrigins.Contains(origin);
  64. })
  65. //.AllowAnyOrigin()
  66. .AllowAnyHeader()
  67. .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
  68. .AllowCredentials());
  69. });
  70. #endregion
  71. #region 上传文件
  72. builder.Services.AddCors(policy =>
  73. {
  74. policy.AddPolicy("Cors", opt => opt
  75. .AllowAnyOrigin()
  76. .AllowAnyHeader()
  77. .AllowAnyMethod()
  78. .WithExposedHeaders("X-Pagination"));
  79. });
  80. builder.Services.Configure<FormOptions>(options =>
  81. {
  82. options.KeyLengthLimit = int.MaxValue;
  83. options.ValueLengthLimit = int.MaxValue;
  84. options.MultipartBodyLengthLimit = int.MaxValue;
  85. options.MultipartHeadersLengthLimit = int.MaxValue;
  86. });
  87. builder.Services.Configure<KestrelServerOptions>(options =>
  88. {
  89. options.Limits.MaxRequestBodySize = int.MaxValue;
  90. options.Limits.MaxRequestBufferSize = int.MaxValue;
  91. });
  92. #endregion
  93. #region 接口分组
  94. var groups = new List<Tuple<string, string>>
  95. {
  96. //new Tuple<string, string>("Group1","分组一"),
  97. //new Tuple<string, string>("Group2","分组二")
  98. };
  99. #endregion
  100. #region 注入数据库
  101. builder.Services.AddScoped(options =>
  102. {
  103. return new SqlSugarClient(new List<ConnectionConfig>()
  104. {
  105. new ConnectionConfig() {
  106. ConfigId = DBEnum.OA2023DB,
  107. ConnectionString = _config.GetConnectionString("OA2023DB"),
  108. DbType = DbType.SqlServer,
  109. IsAutoCloseConnection = true
  110. },
  111. new ConnectionConfig()
  112. {
  113. ConfigId = DBEnum.OA2014DB,
  114. ConnectionString = _config.GetConnectionString("OA2014DB"),
  115. DbType = DbType.SqlServer,
  116. IsAutoCloseConnection = true },
  117. }
  118. , db =>
  119. {
  120. //SQL执行完
  121. db.Aop.OnLogExecuted = (sql, pars) =>
  122. {
  123. //if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
  124. //{
  125. //代码CS文件名
  126. var fileName = db.Ado.SqlStackTrace.FirstFileName;
  127. //代码行数
  128. var fileLine = db.Ado.SqlStackTrace.FirstLine;
  129. //方法名
  130. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  131. //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
  132. Console.WriteLine("NowTime:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
  133. Console.WriteLine("MethodName:" + FirstMethodName);
  134. Console.WriteLine("ElapsedTime:" + db.Ado.SqlExecutionTime.ToString());
  135. Console.WriteLine("ExecuteSQL:" + sql);
  136. //}
  137. };
  138. //SQL执行前
  139. db.Aop.OnLogExecuting = (sql, pars) =>
  140. {
  141. //获取原生SQL推荐 5.1.4.63 性能OK
  142. //UtilMethods.GetNativeSql(sql, pars);
  143. //获取无参数化SQL 影响性能只适合调试
  144. //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
  145. };
  146. //SQL报错
  147. db.Aop.OnError = (exp) =>
  148. {
  149. //获取原生SQL推荐 5.1.4.63 性能OK
  150. //UtilMethods.GetNativeSql(exp.sql, exp.parameters);
  151. //获取无参数SQL对性能有影响,特别大的SQL参数多的,调试使用
  152. //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
  153. };
  154. //修改SQL和参数的值
  155. db.Aop.OnExecutingChangeSql = (sql, pars) =>
  156. {
  157. //sql=newsql
  158. //foreach(var p in pars) //修改
  159. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  160. };
  161. }
  162. );
  163. });
  164. #endregion
  165. //#region Identity 配置
  166. //builder.Services.AddDataProtection();
  167. ////不要用 AddIdentity , AddIdentity 是于MVC框架中的
  168. //builder.Services.AddIdentityCore<User>(opt =>
  169. //{
  170. // opt.Password.RequireDigit = false; //数字
  171. // opt.Password.RequireLowercase = false;//小写字母
  172. // opt.Password.RequireNonAlphanumeric = false;//特殊符号 例如 ¥#@!
  173. // opt.Password.RequireUppercase = false; //大写字母
  174. // opt.Password.RequiredLength = 6;//密码长度 6
  175. // opt.Password.RequiredUniqueChars = 1;//相同字符可以出现几次
  176. // opt.Lockout.MaxFailedAccessAttempts = 5; //允许最多输入五次用户名/密码错误
  177. // opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 5, 0);//锁定五分钟
  178. // opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; // 修改密码使用邮件【验证码模式】
  179. // opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; ////
  180. //});
  181. //var idBuilder = new IdentityBuilder(typeof(User), typeof(UserRole), services);
  182. //idBuilder.AddEntityFrameworkStores<swapDbContext>().AddDefaultTokenProviders().AddRoleManager<RoleManager<UserRole>>().AddUserManager<UserManager<User>>();
  183. //#endregion
  184. #region 注入Swagger注释(启用)
  185. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  186. {
  187. builder.Services.AddSwaggerGen(a =>
  188. {
  189. a.SwaggerDoc("v1", new OpenApiInfo
  190. {
  191. Version = "v1",
  192. Title = "Api",
  193. Description = "Api接口文档"
  194. });
  195. foreach (var item in groups)
  196. {
  197. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  198. }
  199. a.DocumentFilter<SwaggerApi>();
  200. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  201. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  202. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  203. {
  204. Description = "Value: Bearer {token}",
  205. Name = "Authorization",
  206. In = ParameterLocation.Header,
  207. Type = SecuritySchemeType.ApiKey,
  208. Scheme = "Bearer"
  209. });
  210. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  211. {{
  212. new OpenApiSecurityScheme
  213. {
  214. Reference = new OpenApiReference
  215. {
  216. Type = ReferenceType.SecurityScheme,
  217. Id = "Bearer"
  218. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  219. }
  220. });
  221. });
  222. }
  223. #endregion
  224. #region 添加校验
  225. builder.Services.AddTransient<OASystemAuthentication>();
  226. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  227. .AddJwtBearer(options =>
  228. {
  229. options.TokenValidationParameters = new TokenValidationParameters
  230. {
  231. ValidateIssuer = true,
  232. ValidateAudience = true,
  233. ValidateLifetime = true,
  234. ValidateIssuerSigningKey = true,
  235. ValidAudience = "OASystem.com",
  236. ValidIssuer = "OASystem.com",
  237. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  238. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  239. RequireExpirationTime = true,
  240. };
  241. options.Events = new JwtBearerEvents
  242. {
  243. OnMessageReceived = context =>
  244. {
  245. var path = context.HttpContext.Request.Path;
  246. //如果是signalr请求,需要将token转存,否则JWT获取不到token。OPTIONS请求需要过滤到,因为OPTIONS请求获取不到Token,用NGINX过滤掉OPTION请求.
  247. if (path.StartsWithSegments("/ChatHub"))
  248. {
  249. string accessToken = context.Request.Query["access_token"].ToString();
  250. if (string.IsNullOrWhiteSpace(accessToken))
  251. {
  252. accessToken = context.Request.Headers["Authorization"].ToString();
  253. }
  254. context.Token = accessToken.Replace("Bearer ", "").Trim();
  255. }
  256. return Task.CompletedTask;
  257. }
  258. };
  259. });
  260. #endregion
  261. #region 初始化日志
  262. Log.Logger = new LoggerConfiguration()
  263. .MinimumLevel.Debug()
  264. .Enrich.FromLogContext()
  265. .WriteTo.Console()
  266. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  267. .CreateLogger();
  268. // 配置Serilog为Log;
  269. builder.Host.UseSerilog();
  270. #endregion
  271. #region 引入注册Autofac Module
  272. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  273. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  274. {
  275. try
  276. {
  277. builder.RegisterModule(new AutofacRegister());
  278. }
  279. catch (Exception ex)
  280. {
  281. throw new Exception(ex.Message + "\n" + ex.InnerException);
  282. }
  283. });
  284. #endregion
  285. #region AutoMapper
  286. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  287. {
  288. cfg.AddProfile<_baseMappingProfile>();
  289. });
  290. builder.Services.AddSingleton(config);
  291. builder.Services.AddScoped<IMapper, Mapper>();
  292. #endregion
  293. #region 聚合API 服务
  294. builder.Services.AddControllersWithViews();
  295. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  296. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  297. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  298. #endregion
  299. #region 企业微信API 服务
  300. builder.Services.AddControllersWithViews();
  301. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  302. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  303. #endregion
  304. #region 有道API 服务
  305. //builder.Services.AddControllersWithViews();
  306. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  307. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  308. #endregion
  309. #region 高德地图API 服务
  310. builder.Services.AddHttpClient<GeocodeService>();
  311. #endregion
  312. #region Quartz
  313. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  314. builder.Services.AddSingleton<QuartzFactory>();
  315. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  316. builder.Services.AddSingleton<TaskJob>();
  317. builder.Services.AddSingleton<TaskNewsFeedJob>();
  318. //# new business
  319. builder.Services.AddControllersWithViews();
  320. builder.Services.AddSingleton<IAPNsService, APNsService>();
  321. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  322. #endregion
  323. #region SignalR
  324. builder.Services.AddSignalR()
  325. .AddJsonProtocol(options =>
  326. {
  327. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  328. });
  329. builder.Services.TryAddSingleton(typeof(CommonService));
  330. #endregion
  331. #region 健康检查服务
  332. ////
  333. //builder.Services.AddHealthChecks()
  334. // .AddCheck("ExampleHealthCheck", () =>
  335. // HealthCheckResult.Healthy("Everything is OK!"), tags: new[] { "example" });
  336. //// 添加 HealthChecks UI 服务
  337. //builder.Services.AddHealthChecksUI(setup =>
  338. //{
  339. // setup.SetEvaluationTimeInSeconds(60); // 每 60 秒检查一次
  340. // setup.MaximumHistoryEntriesPerEndpoint(50); // 每个端点最多保存 50 条历史记录
  341. // setup.SetApiMaxActiveRequests(1); // UI API 的最大并发请求数
  342. //})
  343. //.AddInMemoryStorage(); // 使用内存存储健康检查结果
  344. #endregion
  345. var app = builder.Build();
  346. //serilog日志 请求中间管道
  347. app.UseSerilogRequestLogging(options =>
  348. {
  349. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000}ms";
  350. });
  351. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  352. // Configure the HTTP request pipeline.
  353. if (!app.Environment.IsDevelopment())
  354. {
  355. app.UseExceptionHandler("/Home/Error");
  356. }
  357. app.UseStaticFiles();
  358. app.UseRouting();
  359. app.UseCors("Cors"); //Cors
  360. //app.UseMiddleware<FixedPromptMiddleware>();
  361. app.UseMiddleware<ExceptionHandlingMiddleware>();
  362. // 定义允许API的访问时间段
  363. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  364. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  365. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  366. //指定API操作记录信息
  367. app.UseMiddleware<RecordAPIOperationMiddleware>();
  368. app.UseAuthentication(); // 认证
  369. app.UseAuthorization(); // 授权
  370. // 授权路径
  371. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  372. #region 启用swaggerUI
  373. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  374. {
  375. app.UseSwagger();
  376. app.UseSwaggerUI(c =>
  377. {
  378. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  379. foreach (var item in groups)
  380. {
  381. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  382. }
  383. c.RoutePrefix = string.Empty;
  384. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  385. c.DefaultModelsExpandDepth(-1);
  386. //c.EnableFilter();// 添加搜索功能
  387. //c.EnableDeepLinking(); // 启用深度链接
  388. });
  389. }
  390. #endregion
  391. #region Quartz
  392. //获取容器中的QuartzFactory
  393. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  394. app.Lifetime.ApplicationStarted.Register(async () =>
  395. {
  396. await quartz.Start();
  397. });
  398. app.Lifetime.ApplicationStopped.Register(() =>
  399. {
  400. //Quzrtz关闭方法
  401. //quartz.Stop();
  402. });
  403. #endregion
  404. #region SignalR
  405. app.MapHub<ChatHub>("/ChatHub", options =>
  406. {
  407. options.Transports =
  408. HttpTransportType.WebSockets |
  409. HttpTransportType.LongPolling;
  410. });
  411. #endregion
  412. #region 配置健康检查端点
  413. // 配置健康检查端点
  414. //app.MapHealthChecks("/health", new HealthCheckOptions
  415. //{
  416. // Predicate = _ => true, // 包含所有健康检查
  417. // ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse // 使用 UI 的响应格式
  418. //});
  419. #endregion
  420. app.MapControllerRoute(
  421. name: "default",
  422. pattern: "{controller=Home}/{action=Index}/{id?}");
  423. app.Run();