Program.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. using StackExchange.Redis;
  2. using Autofac.Core;
  3. using OASystem.API;
  4. using OASystem.RedisRepository.RedisAsyncHelper;
  5. using OASystem.RedisRepository.Config;
  6. using OASystem.API.OAMethodLib;
  7. using Microsoft.AspNetCore.Http.Features;
  8. using Microsoft.AspNetCore.Server.Kestrel.Core;
  9. using OASystem.API.OAMethodLib.JuHeAPI;
  10. using OASystem.API.OAMethodLib.YouDaoAPI;
  11. using Quartz.Impl;
  12. using Quartz.Spi;
  13. using Quartz;
  14. using QuzrtzJob.Factory;
  15. using System.Runtime.CompilerServices;
  16. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  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. .Build();
  24. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  25. // Add services to the container.
  26. builder.Services.AddControllersWithViews();
  27. builder.Services.AddControllers()
  28. .AddJsonOptions(options =>
  29. {
  30. //空字段不响应Response
  31. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  32. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  33. //时间格式化响应
  34. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  35. ////decimal 四位小数
  36. //options.JsonSerializerOptions.Converters.Add(new JsonConverterDecimal(0.0000M));
  37. });
  38. #region Cors
  39. builder.Services.AddCors(policy =>
  40. {
  41. policy.AddPolicy("Cors", opt => opt
  42. .AllowAnyOrigin()
  43. .AllowAnyHeader()
  44. .AllowAnyMethod()
  45. .WithExposedHeaders("X-Pagination"));
  46. });
  47. #endregion
  48. #region 上传文件
  49. builder.Services.AddCors(policy =>
  50. {
  51. policy.AddPolicy("Cors", opt => opt
  52. .AllowAnyOrigin()
  53. .AllowAnyHeader()
  54. .AllowAnyMethod()
  55. .WithExposedHeaders("X-Pagination"));
  56. });
  57. builder.Services.Configure<FormOptions>(options =>
  58. {
  59. options.KeyLengthLimit = int.MaxValue;
  60. options.ValueLengthLimit = int.MaxValue;
  61. options.MultipartBodyLengthLimit = int.MaxValue;
  62. options.MultipartHeadersLengthLimit = int.MaxValue;
  63. });
  64. builder.Services.Configure<KestrelServerOptions>(options =>
  65. {
  66. options.Limits.MaxRequestBodySize = int.MaxValue;
  67. options.Limits.MaxRequestBufferSize = int.MaxValue;
  68. });
  69. #endregion
  70. #region 接口分组
  71. var groups = new List<Tuple<string, string>>
  72. {
  73. //new Tuple<string, string>("Group1","分组一"),
  74. //new Tuple<string, string>("Group2","分组二")
  75. };
  76. #endregion
  77. #region 注入数据库
  78. builder.Services.AddScoped(options =>
  79. {
  80. return new SqlSugarClient(new List<ConnectionConfig>()
  81. {
  82. new ConnectionConfig() {
  83. ConfigId = DBEnum.OA2023DB,
  84. ConnectionString = _config.GetConnectionString("OA2023DB"),
  85. DbType = DbType.SqlServer, IsAutoCloseConnection = true },
  86. new ConnectionConfig()
  87. {
  88. ConfigId = DBEnum.OA2014DB,
  89. ConnectionString = _config.GetConnectionString("OA2014DB"),
  90. DbType = DbType.SqlServer, IsAutoCloseConnection = true },
  91. });
  92. });
  93. #endregion
  94. #region 注入Swagger注释(启用)
  95. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  96. {
  97. builder.Services.AddSwaggerGen(a =>
  98. {
  99. a.SwaggerDoc("v1", new OpenApiInfo
  100. {
  101. Version = "v1",
  102. Title = "Api",
  103. Description = "Api接口文档"
  104. });
  105. foreach (var item in groups)
  106. {
  107. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  108. }
  109. a.DocumentFilter<SwaggerApi>();
  110. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  111. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  112. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  113. {
  114. Description = "Value: Bearer {token}",
  115. Name = "Authorization",
  116. In = ParameterLocation.Header,
  117. Type = SecuritySchemeType.ApiKey,
  118. Scheme = "Bearer"
  119. });
  120. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  121. {{
  122. new OpenApiSecurityScheme
  123. {
  124. Reference = new OpenApiReference
  125. {
  126. Type = ReferenceType.SecurityScheme,
  127. Id = "Bearer"
  128. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  129. }
  130. });
  131. });
  132. }
  133. #endregion
  134. #region 添加swagger注释
  135. //if (AppSettingsHelper.Get("UseSwagger").ToBool())
  136. //{
  137. // builder.Services.AddSwaggerGen(c =>
  138. // {
  139. // c.SwaggerDoc("v1", new OpenApiInfo
  140. // {
  141. // Version = "v1",
  142. // Title = "文华商旅支付测试接口",
  143. // Description = "请先从Auth鉴权=>login获取token进行认证,输入:token进行认证(Bearer)"
  144. // });
  145. // c.DocumentFilter<SwaggerApi>();
  146. // var xmlPath = Path.Combine(basePath, "OASystem.API.xml");
  147. // c.IncludeXmlComments(xmlPath, true);
  148. // var xmlDomainPath = Path.Combine(basePath, "OASystem.Domain.xml");
  149. // c.IncludeXmlComments(xmlDomainPath, true);
  150. // c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  151. // {
  152. // Description = "Value: Bearer {token}",
  153. // Name = "Authorization",
  154. // In = ParameterLocation.Header,
  155. // Type = SecuritySchemeType.ApiKey,
  156. // Scheme = "Bearer"
  157. // });
  158. // c.AddSecurityRequirement(new OpenApiSecurityRequirement()
  159. // {
  160. // {
  161. // new OpenApiSecurityScheme
  162. // {
  163. // Reference = new OpenApiReference
  164. // {
  165. // Type = ReferenceType.SecurityScheme,
  166. // Id = "Bearer"
  167. // },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
  168. // },new List<string>()
  169. // }
  170. // });
  171. // });
  172. //}
  173. #endregion
  174. #region 添加校验
  175. //builder.Services.AddTransient<OASystemAuthentication>();
  176. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  177. .AddJwtBearer(options =>
  178. {
  179. options.TokenValidationParameters = new TokenValidationParameters
  180. {
  181. ValidateIssuer = true,
  182. ValidateAudience = true,
  183. ValidateLifetime = true,
  184. ValidateIssuerSigningKey = true,
  185. ValidAudience = "OASystem.com",
  186. ValidIssuer = "OASystem.com",
  187. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  188. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  189. RequireExpirationTime = true,
  190. };
  191. });
  192. #endregion
  193. #region 初始化日志
  194. Log.Logger = new LoggerConfiguration()
  195. .MinimumLevel.Debug()
  196. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  197. .CreateLogger();
  198. #endregion
  199. #region 引入注册Autofac Module
  200. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  201. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  202. {
  203. try
  204. {
  205. builder.RegisterModule(new AutofacRegister());
  206. }
  207. catch (Exception ex)
  208. {
  209. throw new Exception(ex.Message + "\n" + ex.InnerException);
  210. }
  211. });
  212. #endregion
  213. #region AutoMapper
  214. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  215. {
  216. cfg.AddProfile<_baseMappingProfile>();
  217. });
  218. builder.Services.AddSingleton(config);
  219. builder.Services.AddScoped<IMapper, Mapper>();
  220. #endregion
  221. #region 聚合API 服务
  222. builder.Services.AddControllersWithViews();
  223. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  224. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  225. #endregion
  226. #region 企业微信API 服务
  227. builder.Services.AddControllersWithViews();
  228. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  229. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  230. #endregion
  231. #region 有道API 服务
  232. //builder.Services.AddControllersWithViews();
  233. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  234. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  235. #endregion
  236. #region Quartz
  237. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  238. builder.Services.AddSingleton<QuartzFactory>();
  239. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  240. //# new business
  241. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  242. #endregion
  243. var app = builder.Build();
  244. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  245. // Configure the HTTP request pipeline.
  246. if (!app.Environment.IsDevelopment())
  247. {
  248. app.UseExceptionHandler("/Home/Error");
  249. }
  250. app.UseStaticFiles();
  251. app.UseRouting();
  252. app.UseAuthentication(); // 认证
  253. app.UseAuthorization(); // 授权
  254. app.UseCors("Cors"); //Cors
  255. //app.UseCors("AllowSpecificOrigin"); //Cors
  256. #region 启用swaggerUI
  257. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  258. {
  259. app.UseSwagger();
  260. app.UseSwaggerUI(c =>
  261. {
  262. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  263. foreach (var item in groups)
  264. {
  265. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  266. }
  267. c.RoutePrefix = string.Empty;
  268. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  269. c.DefaultModelsExpandDepth(-1);
  270. });
  271. }
  272. #endregion
  273. #region Quartz
  274. //获取容器中的QuartzFactory
  275. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  276. app.Lifetime.ApplicationStarted.Register(async () =>
  277. {
  278. await quartz.Start();
  279. });
  280. app.Lifetime.ApplicationStopped.Register(() =>
  281. {
  282. //Quzrtz关闭方法
  283. //quartz.Stop();
  284. });
  285. #endregion
  286. app.MapControllerRoute(
  287. name: "default",
  288. pattern: "{controller=Home}/{action=Index}/{id?}");
  289. app.Run();