Program.cs 7.5 KB

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