Program.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 System.Text.Json.Serialization;
  8. using OASystem.API.OAMethodLibs;
  9. using OASystem.Domain.Dtos.Groups;
  10. using Microsoft.AspNetCore.Http.Features;
  11. using Microsoft.AspNetCore.Server.Kestrel.Core;
  12. var builder = WebApplication.CreateBuilder(args);
  13. var basePath = AppContext.BaseDirectory;
  14. //引入配置文件
  15. var _config = new ConfigurationBuilder()
  16. .SetBasePath(basePath)
  17. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  18. .Build();
  19. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  20. // Add services to the container.
  21. builder.Services.AddControllersWithViews();
  22. builder.Services.AddControllers()
  23. .AddJsonOptions(options =>
  24. {
  25. //空字段不响应Response
  26. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  27. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  28. //时间格式化响应
  29. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  30. });
  31. #region 上传文件
  32. builder.Services.AddCors(policy =>
  33. {
  34. policy.AddPolicy("Cors", opt => opt
  35. .AllowAnyOrigin()
  36. .AllowAnyHeader()
  37. .AllowAnyMethod()
  38. .WithExposedHeaders("X-Pagination"));
  39. });
  40. builder.Services.Configure<FormOptions>(options =>
  41. {
  42. options.KeyLengthLimit = int.MaxValue;
  43. options.ValueLengthLimit = int.MaxValue;
  44. options.MultipartBodyLengthLimit = int.MaxValue;
  45. options.MultipartHeadersLengthLimit = int.MaxValue;
  46. });
  47. builder.Services.Configure<KestrelServerOptions>(options =>
  48. {
  49. options.Limits.MaxRequestBodySize = int.MaxValue;
  50. options.Limits.MaxRequestBufferSize = int.MaxValue;
  51. });
  52. #endregion
  53. #region 接口分组
  54. var groups = new List<Tuple<string, string>>
  55. {
  56. //new Tuple<string, string>("Group1","分组一"),
  57. //new Tuple<string, string>("Group2","分组二")
  58. };
  59. #endregion
  60. #region 注入数据库
  61. builder.Services.AddScoped(options =>
  62. {
  63. return new SqlSugarClient(new List<ConnectionConfig>()
  64. {
  65. new ConnectionConfig() {
  66. ConfigId = DBEnum.OA2023DB,
  67. ConnectionString = _config.GetConnectionString("OA2023DB"),
  68. DbType = DbType.SqlServer, IsAutoCloseConnection = true }
  69. });
  70. });
  71. #endregion
  72. #region 注入Swagger注释(启用)
  73. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  74. {
  75. builder.Services.AddSwaggerGen(a =>
  76. {
  77. a.SwaggerDoc("v1", new OpenApiInfo
  78. {
  79. Version = "v1",
  80. Title = "Api",
  81. Description = "Api接口文档"
  82. });
  83. foreach (var item in groups)
  84. {
  85. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  86. }
  87. a.DocumentFilter<SwaggerApi>();
  88. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  89. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  90. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  91. {
  92. Description = "Value: Bearer {token}",
  93. Name = "Authorization",
  94. In = ParameterLocation.Header,
  95. Type = SecuritySchemeType.ApiKey,
  96. Scheme = "Bearer"
  97. });
  98. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  99. {{
  100. new OpenApiSecurityScheme
  101. {
  102. Reference = new OpenApiReference
  103. {
  104. Type = ReferenceType.SecurityScheme,
  105. Id = "Bearer"
  106. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  107. }
  108. });
  109. });
  110. }
  111. #endregion
  112. #region 添加swagger注释
  113. //if (AppSettingsHelper.Get("UseSwagger").ToBool())
  114. //{
  115. // builder.Services.AddSwaggerGen(c =>
  116. // {
  117. // c.SwaggerDoc("v1", new OpenApiInfo
  118. // {
  119. // Version = "v1",
  120. // Title = "文华商旅支付测试接口",
  121. // Description = "请先从Auth鉴权=>login获取token进行认证,输入:token进行认证(Bearer)"
  122. // });
  123. // c.DocumentFilter<SwaggerApi>();
  124. // var xmlPath = Path.Combine(basePath, "OASystem.API.xml");
  125. // c.IncludeXmlComments(xmlPath, true);
  126. // var xmlDomainPath = Path.Combine(basePath, "OASystem.Domain.xml");
  127. // c.IncludeXmlComments(xmlDomainPath, true);
  128. // c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  129. // {
  130. // Description = "Value: Bearer {token}",
  131. // Name = "Authorization",
  132. // In = ParameterLocation.Header,
  133. // Type = SecuritySchemeType.ApiKey,
  134. // Scheme = "Bearer"
  135. // });
  136. // c.AddSecurityRequirement(new OpenApiSecurityRequirement()
  137. // {
  138. // {
  139. // new OpenApiSecurityScheme
  140. // {
  141. // Reference = new OpenApiReference
  142. // {
  143. // Type = ReferenceType.SecurityScheme,
  144. // Id = "Bearer"
  145. // },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
  146. // },new List<string>()
  147. // }
  148. // });
  149. // });
  150. //}
  151. #endregion
  152. #region 添加校验
  153. //builder.Services.AddTransient<OASystemAuthentication>();
  154. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  155. .AddJwtBearer(options =>
  156. {
  157. options.TokenValidationParameters = new TokenValidationParameters
  158. {
  159. ValidateIssuer = true,
  160. ValidateAudience = true,
  161. ValidateLifetime = true,
  162. ValidateIssuerSigningKey = true,
  163. ValidAudience = "OASystem.com",
  164. ValidIssuer = "OASystem.com",
  165. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  166. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  167. RequireExpirationTime = true,
  168. };
  169. });
  170. #endregion
  171. #region 初始化日志
  172. Log.Logger = new LoggerConfiguration()
  173. .MinimumLevel.Debug()
  174. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  175. .CreateLogger();
  176. #endregion
  177. #region 引入注册Autofac Module
  178. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  179. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  180. {
  181. try
  182. {
  183. builder.RegisterModule(new AutofacRegister());
  184. }
  185. catch (Exception ex)
  186. {
  187. throw new Exception(ex.Message + "\n" + ex.InnerException);
  188. }
  189. });
  190. #endregion
  191. #region AutoMapper
  192. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  193. {
  194. cfg.AddProfile<_baseMappingProfile>();
  195. });
  196. builder.Services.AddSingleton(config);
  197. builder.Services.AddScoped<IMapper, Mapper>();
  198. #endregion
  199. var app = builder.Build();
  200. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  201. // Configure the HTTP request pipeline.
  202. if (!app.Environment.IsDevelopment())
  203. {
  204. app.UseExceptionHandler("/Home/Error");
  205. }
  206. app.UseStaticFiles();
  207. app.UseRouting();
  208. app.UseAuthentication(); // 认证
  209. app.UseAuthorization(); // 授权
  210. app.UseCors("Cors"); //Cors
  211. //app.UseCors("AllowSpecificOrigin"); //Cors
  212. #region 启用swaggerUI
  213. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  214. {
  215. app.UseSwagger();
  216. app.UseSwaggerUI(c =>
  217. {
  218. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  219. foreach (var item in groups)
  220. {
  221. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  222. }
  223. c.RoutePrefix = string.Empty;
  224. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  225. c.DefaultModelsExpandDepth(-1);
  226. });
  227. }
  228. #endregion
  229. app.MapControllerRoute(
  230. name: "default",
  231. pattern: "{controller=Home}/{action=Index}/{id?}");
  232. app.Run();