Program.cs 14 KB

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