0
0

BaseStartup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. using AspNetCoreRateLimit;
  2. using Autofac;
  3. using IdentityServer4.AccessTokenValidation;
  4. using Microsoft.AspNetCore.Authentication;
  5. using Microsoft.AspNetCore.Authentication.JwtBearer;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.DependencyInjection.Extensions;
  12. using Microsoft.Extensions.Hosting;
  13. using Microsoft.Extensions.DependencyModel;
  14. using Microsoft.IdentityModel.Tokens;
  15. using Microsoft.OpenApi.Models;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Serialization;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.IdentityModel.Tokens.Jwt;
  21. using System.Linq;
  22. using System.Reflection;
  23. using System.Text;
  24. using Mapster;
  25. using Yitter.IdGenerator;
  26. //using FluentValidation;
  27. //using FluentValidation.AspNetCore;
  28. using ZhonTai.Plate.Admin.HttpApi.Shared.Auth;
  29. using ZhonTai.Common.Auth;
  30. using ZhonTai.Tools.Cache;
  31. using ZhonTai.Common.Configs;
  32. using ZhonTai.Common.Consts;
  33. using ZhonTai.Common.Helpers;
  34. using ZhonTai.Plate.Admin.HttpApi.Shared.Db;
  35. using ZhonTai.Plate.Admin.HttpApi.Shared.Enums;
  36. using ZhonTai.Plate.Admin.HttpApi.Shared.Extensions;
  37. using ZhonTai.Plate.Admin.HttpApi.Shared.Filters;
  38. using ZhonTai.Plate.Admin.HttpApi.Shared.Logs;
  39. using ZhonTai.Plate.Admin.HttpApi.Shared.RegisterModules;
  40. using MapsterMapper;
  41. using StackExchange.Profiling;
  42. using System.IO;
  43. using ZhonTai.Tools.DynamicApi;
  44. namespace ZhonTai.Plate.Admin.HttpApi.Shared
  45. {
  46. public abstract class BaseStartup
  47. {
  48. private static string basePath => AppContext.BaseDirectory;
  49. private readonly IConfiguration _configuration;
  50. private readonly IHostEnvironment _env;
  51. private readonly ConfigHelper _configHelper;
  52. private readonly AppConfig _appConfig;
  53. private const string DefaultCorsPolicyName = "AllowPolicy";
  54. public BaseStartup(IConfiguration configuration, IWebHostEnvironment env)
  55. {
  56. _configuration = configuration;
  57. _env = env;
  58. _configHelper = new ConfigHelper();
  59. _appConfig = _configHelper.Get<AppConfig>("appconfig", env.EnvironmentName) ?? new AppConfig();
  60. }
  61. public virtual void ConfigureServices(IServiceCollection services)
  62. {
  63. //雪花漂移算法
  64. YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1) { WorkerIdBitLength = 6 });
  65. //权限处理
  66. services.AddScoped<IPermissionHandler, PermissionHandler>();
  67. // ClaimType不被更改
  68. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  69. //用户信息
  70. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  71. if (_appConfig.IdentityServer.Enable)
  72. {
  73. //is4
  74. services.TryAddSingleton<IUser, UserIdentiyServer>();
  75. }
  76. else
  77. {
  78. //jwt
  79. services.TryAddSingleton<IUser, User>();
  80. }
  81. //添加数据库
  82. services.AddDbAsync(_env).Wait();
  83. //添加IdleBus单例
  84. var dbConfig = new ConfigHelper().Get<DbConfig>("dbconfig", _env.EnvironmentName);
  85. var timeSpan = dbConfig.IdleTime > 0 ? TimeSpan.FromMinutes(dbConfig.IdleTime) : TimeSpan.MaxValue;
  86. IdleBus<IFreeSql> ib = new IdleBus<IFreeSql>(timeSpan);
  87. services.AddSingleton(ib);
  88. //数据库配置
  89. services.AddSingleton(dbConfig);
  90. //应用配置
  91. services.AddSingleton(_appConfig);
  92. //上传配置
  93. var uploadConfig = _configHelper.Load("uploadconfig", _env.EnvironmentName, true);
  94. services.Configure<UploadConfig>(uploadConfig);
  95. #region Mapster 映射配置
  96. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  97. .Where(a => a.Name.StartsWith("ZhonTai"))
  98. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  99. services.AddScoped<IMapper>(sp => new Mapper());
  100. TypeAdapterConfig.GlobalSettings.Scan(assemblies);
  101. #endregion Mapster 映射配置
  102. #region Cors 跨域
  103. services.AddCors(options =>
  104. {
  105. options.AddPolicy(DefaultCorsPolicyName, policy =>
  106. {
  107. var hasOrigins = _appConfig.CorUrls?.Length > 0;
  108. if (hasOrigins)
  109. {
  110. policy.WithOrigins(_appConfig.CorUrls);
  111. }
  112. else
  113. {
  114. policy.AllowAnyOrigin();
  115. }
  116. policy
  117. .AllowAnyHeader()
  118. .AllowAnyMethod();
  119. if (hasOrigins)
  120. {
  121. policy.AllowCredentials();
  122. }
  123. });
  124. //允许任何源访问Api策略,使用时在控制器或者接口上增加特性[EnableCors(AdminConsts.AllowAnyPolicyName)]
  125. options.AddPolicy(AdminConsts.AllowAnyPolicyName, policy =>
  126. {
  127. policy
  128. .AllowAnyOrigin()
  129. .AllowAnyHeader()
  130. .AllowAnyMethod();
  131. });
  132. /*
  133. //浏览器会发起2次请求,使用OPTIONS发起预检请求,第二次才是api异步请求
  134. options.AddPolicy("All", policy =>
  135. {
  136. policy
  137. .AllowAnyOrigin()
  138. .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
  139. .AllowAnyHeader()
  140. .AllowAnyMethod();
  141. });
  142. */
  143. });
  144. #endregion Cors 跨域
  145. #region 身份认证授权
  146. var jwtConfig = _configHelper.Get<JwtConfig>("jwtconfig", _env.EnvironmentName);
  147. services.TryAddSingleton(jwtConfig);
  148. if (_appConfig.IdentityServer.Enable)
  149. {
  150. //is4
  151. services.AddAuthentication(options =>
  152. {
  153. options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
  154. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  155. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  156. })
  157. .AddJwtBearer(options =>
  158. {
  159. options.Authority = _appConfig.IdentityServer.Url;
  160. options.RequireHttpsMetadata = false;
  161. options.Audience = "admin.server.api";
  162. })
  163. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  164. }
  165. else
  166. {
  167. //jwt
  168. services.AddAuthentication(options =>
  169. {
  170. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  171. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  172. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  173. })
  174. .AddJwtBearer(options =>
  175. {
  176. options.TokenValidationParameters = new TokenValidationParameters
  177. {
  178. ValidateIssuer = true,
  179. ValidateAudience = true,
  180. ValidateLifetime = true,
  181. ValidateIssuerSigningKey = true,
  182. ValidIssuer = jwtConfig.Issuer,
  183. ValidAudience = jwtConfig.Audience,
  184. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  185. ClockSkew = TimeSpan.Zero
  186. };
  187. })
  188. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  189. }
  190. #endregion 身份认证授权
  191. #region Swagger Api文档
  192. if (_env.IsDevelopment() || _appConfig.Swagger)
  193. {
  194. services.AddSwaggerGen(options =>
  195. {
  196. typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
  197. {
  198. options.SwaggerDoc(version, new OpenApiInfo
  199. {
  200. Version = version,
  201. Title = "ZhonTai.Plate.Admin.Host"
  202. });
  203. //c.OrderActionsBy(o => o.RelativePath);
  204. });
  205. options.ResolveConflictingActions(apiDescription => apiDescription.First());
  206. options.CustomSchemaIds(x => x.FullName);
  207. options.DocInclusionPredicate((docName, description) => true);
  208. string[] xmlFiles = Directory.GetFiles(basePath, "*.xml");
  209. if (xmlFiles.Length > 0)
  210. {
  211. foreach (var xmlFile in xmlFiles)
  212. {
  213. options.IncludeXmlComments(xmlFile, true);
  214. }
  215. }
  216. #region 添加设置Token的按钮
  217. if (_appConfig.IdentityServer.Enable)
  218. {
  219. //添加Jwt验证设置
  220. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  221. {
  222. {
  223. new OpenApiSecurityScheme
  224. {
  225. Reference = new OpenApiReference
  226. {
  227. Id = "oauth2",
  228. Type = ReferenceType.SecurityScheme
  229. }
  230. },
  231. new List<string>()
  232. }
  233. });
  234. //统一认证
  235. options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
  236. {
  237. Type = SecuritySchemeType.OAuth2,
  238. Description = "oauth2登录授权",
  239. Flows = new OpenApiOAuthFlows
  240. {
  241. Implicit = new OpenApiOAuthFlow
  242. {
  243. AuthorizationUrl = new Uri($"{_appConfig.IdentityServer.Url}/connect/authorize"),
  244. Scopes = new Dictionary<string, string>
  245. {
  246. { "admin.server.api", "admin后端api" }
  247. }
  248. }
  249. }
  250. });
  251. }
  252. else
  253. {
  254. //添加Jwt验证设置
  255. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  256. {
  257. {
  258. new OpenApiSecurityScheme
  259. {
  260. Reference = new OpenApiReference
  261. {
  262. Id = "Bearer",
  263. Type = ReferenceType.SecurityScheme
  264. }
  265. },
  266. new List<string>()
  267. }
  268. });
  269. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  270. {
  271. Description = "Value: Bearer {token}",
  272. Name = "Authorization",
  273. In = ParameterLocation.Header,
  274. Type = SecuritySchemeType.ApiKey
  275. });
  276. }
  277. #endregion 添加设置Token的按钮
  278. });
  279. }
  280. #endregion Swagger Api文档
  281. #region 操作日志
  282. if (_appConfig.Log.Operation)
  283. {
  284. services.AddScoped<ILogHandler, LogHandler>();
  285. }
  286. #endregion 操作日志
  287. #region 控制器
  288. services.AddControllers(options =>
  289. {
  290. options.Filters.Add<ControllerExceptionFilter>();
  291. if (_appConfig.Log.Operation)
  292. {
  293. options.Filters.Add<ControllerLogFilter>();
  294. }
  295. //禁止去除ActionAsync后缀
  296. //options.SuppressAsyncSuffixInActionNames = false;
  297. })
  298. //.AddFluentValidation(config =>
  299. //{
  300. // var assembly = Assembly.LoadFrom(Path.Combine(basePath, "ZhonTai.Plate.Admin.Host.dll"));
  301. // config.RegisterValidatorsFromAssembly(assembly);
  302. //})
  303. .AddNewtonsoftJson(options =>
  304. {
  305. //忽略循环引用
  306. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  307. //使用驼峰 首字母小写
  308. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  309. //设置时间格式
  310. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  311. })
  312. .AddControllersAsServices();
  313. #endregion 控制器
  314. #region 缓存
  315. var cacheConfig = _configHelper.Get<CacheConfig>("cacheconfig", _env.EnvironmentName);
  316. if (cacheConfig.Type == CacheType.Redis)
  317. {
  318. var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
  319. RedisHelper.Initialization(csredis);
  320. services.AddSingleton<ICacheTool, RedisCacheTool>();
  321. }
  322. else
  323. {
  324. services.AddMemoryCache();
  325. services.AddSingleton<ICacheTool, MemoryCacheTool>();
  326. }
  327. #endregion 缓存
  328. #region IP限流
  329. if (_appConfig.RateLimit)
  330. {
  331. services.AddIpRateLimit(_configuration, cacheConfig);
  332. }
  333. #endregion IP限流
  334. //阻止NLog接收状态消息
  335. services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
  336. //性能分析
  337. if (_appConfig.MiniProfiler)
  338. {
  339. services.AddMiniProfiler();
  340. }
  341. services.AddDynamicApi(options =>
  342. {
  343. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  344. .Where(a => a.Name.EndsWith("Service"))
  345. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  346. options.AddAssemblyOptions(assemblies);
  347. });
  348. }
  349. public virtual void ConfigureContainer(ContainerBuilder builder)
  350. {
  351. #region AutoFac IOC容器
  352. try
  353. {
  354. // 控制器注入
  355. builder.RegisterModule(new ControllerModule());
  356. // 单例注入
  357. builder.RegisterModule(new SingleInstanceModule());
  358. // 仓储注入
  359. builder.RegisterModule(new RepositoryModule());
  360. // 服务注入
  361. builder.RegisterModule(new ServiceModule(_appConfig));
  362. }
  363. catch (Exception ex)
  364. {
  365. throw new Exception(ex.Message + "\n" + ex.InnerException);
  366. }
  367. #endregion AutoFac IOC容器
  368. }
  369. public virtual void Configure(IApplicationBuilder app)
  370. {
  371. #region app配置
  372. //IP限流
  373. if (_appConfig.RateLimit)
  374. {
  375. app.UseIpRateLimiting();
  376. }
  377. //性能分析
  378. if (_appConfig.MiniProfiler)
  379. {
  380. app.UseMiniProfiler();
  381. }
  382. //异常
  383. app.UseExceptionHandler("/Error");
  384. //静态文件
  385. app.UseDefaultFiles();
  386. app.UseStaticFiles();
  387. app.UseUploadConfig();
  388. //路由
  389. app.UseRouting();
  390. //跨域
  391. app.UseCors(DefaultCorsPolicyName);
  392. //认证
  393. app.UseAuthentication();
  394. //授权
  395. app.UseAuthorization();
  396. //配置端点
  397. app.UseEndpoints(endpoints =>
  398. {
  399. endpoints.MapControllers();
  400. });
  401. #endregion app配置
  402. #region Swagger Api文档
  403. if (_env.IsDevelopment() || _appConfig.Swagger)
  404. {
  405. app.UseSwagger();
  406. app.UseSwaggerUI(c =>
  407. {
  408. typeof(ApiVersion).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
  409. {
  410. c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"ZhonTai.Plate.Admin.Host {version}");
  411. });
  412. c.RoutePrefix = "";//直接根目录访问,如果是IIS发布可以注释该语句,并打开launchSettings.launchUrl
  413. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//折叠Api
  414. //c.DefaultModelsExpandDepth(-1);//不显示Models
  415. if (_appConfig.MiniProfiler)
  416. {
  417. c.InjectJavascript("/swagger/mini-profiler.js?v=4.2.22");
  418. }
  419. });
  420. }
  421. #endregion Swagger Api文档
  422. //数据库日志
  423. //var log = LogManager.GetLogger("db");
  424. //var ei = new LogEventInfo(LogLevel.Error, "", "错误信息");
  425. //ei.Properties["id"] = YitIdHelper.NextId();
  426. //log.Log(ei);
  427. }
  428. }
  429. }