Program.cs 14 KB

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