Program.cs 15 KB

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