Program.cs 18 KB

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