Startup.cs 19 KB

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