Program.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using StackExchange.Redis;
  2. using Autofac.Core;
  3. var builder = WebApplication.CreateBuilder(args);
  4. var basePath = AppContext.BaseDirectory;
  5. //引入配置文件
  6. var _config = new ConfigurationBuilder()
  7. .SetBasePath(basePath)
  8. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  9. .Build();
  10. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  11. // Add services to the container.
  12. builder.Services.AddControllersWithViews();
  13. #region redis
  14. //redis缓存
  15. var section = builder.Configuration.GetSection("Redis:Default");
  16. //连接字符串
  17. string _connectionString = section.GetSection("Connection").Value;
  18. //实例名称
  19. string _instanceName = section.GetSection("InstanceName").Value;
  20. //默认数据库
  21. int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");
  22. builder.Services.AddSingleton(new RedisHelper(_connectionString+",password=123456", _instanceName, _defaultDB));
  23. #endregion
  24. #region 接口分组
  25. var groups = new List<Tuple<string, string>>
  26. {
  27. //new Tuple<string, string>("Group1","分组一"),
  28. //new Tuple<string, string>("Group2","分组二")
  29. };
  30. #endregion
  31. #region 注入数据库
  32. builder.Services.AddScoped(options =>
  33. {
  34. return new SqlSugarClient(new List<ConnectionConfig>()
  35. {
  36. new ConnectionConfig() {
  37. ConfigId = DBEnum.OA2023DB,
  38. ConnectionString = _config.GetConnectionString("OA2023DB"),
  39. DbType = DbType.SqlServer, IsAutoCloseConnection = true }
  40. });
  41. });
  42. #endregion
  43. #region 注入Swagger注释(启用)
  44. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  45. {
  46. builder.Services.AddSwaggerGen(a =>
  47. {
  48. a.SwaggerDoc("v1", new OpenApiInfo
  49. {
  50. Version = "v1",
  51. Title = "Api",
  52. Description = "Api接口文档"
  53. });
  54. foreach (var item in groups)
  55. {
  56. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  57. }
  58. a.DocumentFilter<SwaggerApi>();
  59. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  60. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  61. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  62. {
  63. Description = "Value: Bearer {token}",
  64. Name = "Authorization",
  65. In = ParameterLocation.Header,
  66. Type = SecuritySchemeType.ApiKey,
  67. Scheme = "Bearer"
  68. });
  69. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  70. {{
  71. new OpenApiSecurityScheme
  72. {
  73. Reference = new OpenApiReference
  74. {
  75. Type = ReferenceType.SecurityScheme,
  76. Id = "Bearer"
  77. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  78. }
  79. });
  80. });
  81. }
  82. #endregion
  83. #region 添加swagger注释
  84. //if (AppSettingsHelper.Get("UseSwagger").ToBool())
  85. //{
  86. // builder.Services.AddSwaggerGen(c =>
  87. // {
  88. // c.SwaggerDoc("v1", new OpenApiInfo
  89. // {
  90. // Version = "v1",
  91. // Title = "文华商旅支付测试接口",
  92. // Description = "请先从Auth鉴权=>login获取token进行认证,输入:token进行认证(Bearer)"
  93. // });
  94. // c.DocumentFilter<SwaggerApi>();
  95. // var xmlPath = Path.Combine(basePath, "OASystem.API.xml");
  96. // c.IncludeXmlComments(xmlPath, true);
  97. // var xmlDomainPath = Path.Combine(basePath, "OASystem.Domain.xml");
  98. // c.IncludeXmlComments(xmlDomainPath, true);
  99. // c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  100. // {
  101. // Description = "Value: Bearer {token}",
  102. // Name = "Authorization",
  103. // In = ParameterLocation.Header,
  104. // Type = SecuritySchemeType.ApiKey,
  105. // Scheme = "Bearer"
  106. // });
  107. // c.AddSecurityRequirement(new OpenApiSecurityRequirement()
  108. // {
  109. // {
  110. // new OpenApiSecurityScheme
  111. // {
  112. // Reference = new OpenApiReference
  113. // {
  114. // Type = ReferenceType.SecurityScheme,
  115. // Id = "Bearer"
  116. // },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
  117. // },new List<string>()
  118. // }
  119. // });
  120. // });
  121. //}
  122. #endregion
  123. #region 添加校验
  124. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
  125. {
  126. options.TokenValidationParameters = new TokenValidationParameters
  127. {
  128. ValidateIssuer = true,
  129. ValidateAudience = true,
  130. ValidateLifetime = true,
  131. ValidateIssuerSigningKey = true,
  132. ValidAudience = "OASystem.com",
  133. ValidIssuer = "OASystem.com",
  134. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  135. };
  136. });
  137. #endregion
  138. #region 初始化日志
  139. Log.Logger = new LoggerConfiguration()
  140. .MinimumLevel.Debug()
  141. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  142. .CreateLogger();
  143. #endregion
  144. #region 引入注册Autofac OASystem.Infrastructure中所有以Repository结尾的文件都会被注入到项目
  145. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  146. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  147. {
  148. try
  149. {
  150. var assemblyServices = Assembly.Load("OASystem.Infrastructure");
  151. builder.RegisterAssemblyTypes(assemblyServices).Where(a => a.Name.EndsWith("Repository")).AsSelf();
  152. }
  153. catch (Exception ex)
  154. {
  155. throw new Exception(ex.Message + "\n" + ex.InnerException);
  156. }
  157. });
  158. #endregion
  159. #region AutoMapper
  160. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  161. {
  162. cfg.AddProfile<_baseMappingProfile>();
  163. });
  164. builder.Services.AddSingleton(config);
  165. builder.Services.AddScoped<IMapper, Mapper>();
  166. #endregion
  167. #region 跨域配置
  168. builder.Services.AddCors(c =>
  169. {
  170. c.AddPolicy("AllowAllOrigins", policy =>
  171. {
  172. policy.AllowAnyOrigin()
  173. .AllowAnyMethod()
  174. .AllowAnyHeader();
  175. });
  176. });
  177. #endregion
  178. var app = builder.Build();
  179. app.UseCors("AllowAllOrigins");
  180. // Configure the HTTP request pipeline.
  181. if (!app.Environment.IsDevelopment())
  182. {
  183. app.UseExceptionHandler("/Home/Error");
  184. }
  185. app.UseStaticFiles();
  186. app.UseRouting();
  187. app.UseAuthentication();
  188. app.UseAuthorization();
  189. #region 启用swaggerUI
  190. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  191. {
  192. app.UseSwagger();
  193. app.UseSwaggerUI(c =>
  194. {
  195. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  196. foreach (var item in groups)
  197. {
  198. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  199. }
  200. c.RoutePrefix = string.Empty;
  201. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  202. c.DefaultModelsExpandDepth(-1);
  203. });
  204. }
  205. #endregion
  206. app.MapControllerRoute(
  207. name: "default",
  208. pattern: "{controller=Home}/{action=Index}/{id?}");
  209. app.Run();