Program.cs 15 KB

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