using StackExchange.Redis; using Autofac.Core; using OASystem.API; using OASystem.RedisRepository.RedisAsyncHelper; using OASystem.RedisRepository.Config; using OASystem.API.OAMethodLib; using System.Text.Json.Serialization; var builder = WebApplication.CreateBuilder(args); var basePath = AppContext.BaseDirectory; //引入配置文件 var _config = new ConfigurationBuilder() .SetBasePath(basePath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); builder.Services.AddSingleton(new AppSettingsHelper(_config)); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddControllers() .AddJsonOptions(options => { //空字段不响应Response options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; //时间格式化响应 options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss")); }); #region Cors builder.Services.AddCors(policy => { policy.AddPolicy("Cors", opt => opt .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .WithExposedHeaders("X-Pagination")); }); #endregion #region 接口分组 var groups = new List> { //new Tuple("Group1","分组一"), //new Tuple("Group2","分组二") }; #endregion #region 注入数据库 builder.Services.AddScoped(options => { return new SqlSugarClient(new List() { new ConnectionConfig() { ConfigId = DBEnum.OA2023DB, ConnectionString = _config.GetConnectionString("OA2023DB"), DbType = DbType.SqlServer, IsAutoCloseConnection = true } }); }); #endregion #region 注入Swagger注释(启用) if (AppSettingsHelper.Get("UseSwagger").ToBool()) { builder.Services.AddSwaggerGen(a => { a.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Api", Description = "Api接口文档" }); foreach (var item in groups) { a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" }); } a.DocumentFilter(); a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true); a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true); a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "Value: Bearer {token}", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); a.AddSecurityRequirement(new OpenApiSecurityRequirement() {{ new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List() } }); }); } #endregion #region 添加swagger注释 //if (AppSettingsHelper.Get("UseSwagger").ToBool()) //{ // builder.Services.AddSwaggerGen(c => // { // c.SwaggerDoc("v1", new OpenApiInfo // { // Version = "v1", // Title = "文华商旅支付测试接口", // Description = "请先从Auth鉴权=>login获取token进行认证,输入:token进行认证(Bearer)" // }); // c.DocumentFilter(); // var xmlPath = Path.Combine(basePath, "OASystem.API.xml"); // c.IncludeXmlComments(xmlPath, true); // var xmlDomainPath = Path.Combine(basePath, "OASystem.Domain.xml"); // c.IncludeXmlComments(xmlDomainPath, true); // c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme // { // Description = "Value: Bearer {token}", // Name = "Authorization", // In = ParameterLocation.Header, // Type = SecuritySchemeType.ApiKey, // Scheme = "Bearer" // }); // c.AddSecurityRequirement(new OpenApiSecurityRequirement() // { // { // new OpenApiSecurityScheme // { // Reference = new OpenApiReference // { // Type = ReferenceType.SecurityScheme, // Id = "Bearer" // },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header, // },new List() // } // }); // }); //} #endregion #region 添加校验 //builder.Services.AddTransient(); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidAudience = "OASystem.com", ValidIssuer = "OASystem.com", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])), ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒) RequireExpirationTime = true, }; }); #endregion #region 初始化日志 Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day) .CreateLogger(); #endregion #region 引入注册Autofac OASystem.Infrastructure中所有以Repository结尾的文件都会被注入到项目 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); var hostBuilder = builder.Host.ConfigureContainer(builder => { try { var assemblyServices = Assembly.Load("OASystem.Infrastructure"); builder.RegisterAssemblyTypes(assemblyServices).Where(a => a.Name.EndsWith("Repository")).AsSelf(); } catch (Exception ex) { throw new Exception(ex.Message + "\n" + ex.InnerException); } }); #endregion #region AutoMapper AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg => { cfg.AddProfile<_baseMappingProfile>(); }); builder.Services.AddSingleton(config); builder.Services.AddScoped(); #endregion var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); // 认证 app.UseAuthorization(); // 授权 app.UseCors("Cors"); //Cors #region 启用swaggerUI if (AppSettingsHelper.Get("UseSwagger").ToBool()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1"); foreach (var item in groups) { c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2); } c.RoutePrefix = string.Empty; c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); c.DefaultModelsExpandDepth(-1); }); } #endregion app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();