Program.cs 19 KB

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