Program.cs 14 KB

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