Program.cs 14 KB

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