0
0

BaseStartup.cs 20 KB

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