Startup.cs 18 KB

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