Program.cs 7.3 KB

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