Program.cs 14 KB

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