Program.cs 19 KB

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