Startup.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. if (_appConfig.CorUrls?.Length > 0)
  97. {
  98. services.AddCors(options =>
  99. {
  100. options.AddPolicy(DefaultCorsPolicyName, policy =>
  101. {
  102. policy
  103. .WithOrigins(_appConfig.CorUrls)
  104. .AllowAnyHeader()
  105. .AllowAnyMethod()
  106. .AllowCredentials();
  107. });
  108. /*
  109. //浏览器会发起2次请求,使用OPTIONS发起预检请求,第二次才是api异步请求
  110. options.AddPolicy("All", policy =>
  111. {
  112. policy
  113. .AllowAnyOrigin()
  114. .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
  115. .AllowAnyHeader()
  116. .AllowAnyMethod()
  117. .AllowCredentials();
  118. });
  119. */
  120. });
  121. }
  122. #endregion Cors 跨域
  123. #region 身份认证授权
  124. var jwtConfig = _configHelper.Get<JwtConfig>("jwtconfig", _env.EnvironmentName);
  125. services.TryAddSingleton(jwtConfig);
  126. if (_appConfig.IdentityServer.Enable)
  127. {
  128. //is4
  129. services.AddAuthentication(options =>
  130. {
  131. options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
  132. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  133. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  134. })
  135. .AddJwtBearer(options =>
  136. {
  137. options.Authority = _appConfig.IdentityServer.Url;
  138. options.RequireHttpsMetadata = false;
  139. options.Audience = "admin.server.api";
  140. })
  141. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  142. }
  143. else
  144. {
  145. //jwt
  146. services.AddAuthentication(options =>
  147. {
  148. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  149. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  150. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  151. })
  152. .AddJwtBearer(options =>
  153. {
  154. options.TokenValidationParameters = new TokenValidationParameters
  155. {
  156. ValidateIssuer = true,
  157. ValidateAudience = true,
  158. ValidateLifetime = true,
  159. ValidateIssuerSigningKey = true,
  160. ValidIssuer = jwtConfig.Issuer,
  161. ValidAudience = jwtConfig.Audience,
  162. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  163. ClockSkew = TimeSpan.Zero
  164. };
  165. })
  166. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  167. }
  168. #endregion 身份认证授权
  169. #region Swagger Api文档
  170. if (_env.IsDevelopment() || _appConfig.Swagger)
  171. {
  172. services.AddSwaggerGen(options =>
  173. {
  174. typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
  175. {
  176. options.SwaggerDoc(version, new OpenApiInfo
  177. {
  178. Version = version,
  179. Title = "Admin.Core"
  180. });
  181. //c.OrderActionsBy(o => o.RelativePath);
  182. });
  183. var xmlPath = Path.Combine(basePath, "Admin.Core.xml");
  184. options.IncludeXmlComments(xmlPath, true);
  185. var xmlCommonPath = Path.Combine(basePath, "Admin.Core.Common.xml");
  186. options.IncludeXmlComments(xmlCommonPath, true);
  187. var xmlModelPath = Path.Combine(basePath, "Admin.Core.Model.xml");
  188. options.IncludeXmlComments(xmlModelPath);
  189. var xmlServicesPath = Path.Combine(basePath, "Admin.Core.Service.xml");
  190. options.IncludeXmlComments(xmlServicesPath);
  191. #region 添加设置Token的按钮
  192. if (_appConfig.IdentityServer.Enable)
  193. {
  194. //添加Jwt验证设置
  195. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  196. {
  197. {
  198. new OpenApiSecurityScheme
  199. {
  200. Reference = new OpenApiReference
  201. {
  202. Id = "oauth2",
  203. Type = ReferenceType.SecurityScheme
  204. }
  205. },
  206. new List<string>()
  207. }
  208. });
  209. //统一认证
  210. options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
  211. {
  212. Type = SecuritySchemeType.OAuth2,
  213. Description = "oauth2登录授权",
  214. Flows = new OpenApiOAuthFlows
  215. {
  216. Implicit = new OpenApiOAuthFlow
  217. {
  218. AuthorizationUrl = new Uri($"{_appConfig.IdentityServer.Url}/connect/authorize"),
  219. Scopes = new Dictionary<string, string>
  220. {
  221. { "admin.server.api", "admin后端api" }
  222. }
  223. }
  224. }
  225. });
  226. }
  227. else
  228. {
  229. //添加Jwt验证设置
  230. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  231. {
  232. {
  233. new OpenApiSecurityScheme
  234. {
  235. Reference = new OpenApiReference
  236. {
  237. Id = "Bearer",
  238. Type = ReferenceType.SecurityScheme
  239. }
  240. },
  241. new List<string>()
  242. }
  243. });
  244. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  245. {
  246. Description = "Value: Bearer {token}",
  247. Name = "Authorization",
  248. In = ParameterLocation.Header,
  249. Type = SecuritySchemeType.ApiKey
  250. });
  251. }
  252. #endregion 添加设置Token的按钮
  253. });
  254. }
  255. #endregion Swagger Api文档
  256. #region 操作日志
  257. if (_appConfig.Log.Operation)
  258. {
  259. //services.AddSingleton<ILogHandler, LogHandler>();
  260. services.AddScoped<ILogHandler, LogHandler>();
  261. }
  262. #endregion 操作日志
  263. #region 控制器
  264. services.AddControllers(options =>
  265. {
  266. options.Filters.Add<AdminExceptionFilter>();
  267. if (_appConfig.Log.Operation)
  268. {
  269. options.Filters.Add<LogActionFilter>();
  270. }
  271. //禁止去除ActionAsync后缀
  272. options.SuppressAsyncSuffixInActionNames = false;
  273. })
  274. //.AddFluentValidation(config =>
  275. //{
  276. // var assembly = Assembly.LoadFrom(Path.Combine(basePath, "Admin.Core.dll"));
  277. // config.RegisterValidatorsFromAssembly(assembly);
  278. //})
  279. .AddNewtonsoftJson(options =>
  280. {
  281. //忽略循环引用
  282. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  283. //使用驼峰 首字母小写
  284. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  285. //设置时间格式
  286. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  287. });
  288. #endregion 控制器
  289. #region 缓存
  290. var cacheConfig = _configHelper.Get<CacheConfig>("cacheconfig", _env.EnvironmentName);
  291. if (cacheConfig.Type == CacheType.Redis)
  292. {
  293. var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
  294. RedisHelper.Initialization(csredis);
  295. services.AddSingleton<ICache, RedisCache>();
  296. }
  297. else
  298. {
  299. services.AddMemoryCache();
  300. services.AddSingleton<ICache, MemoryCache>();
  301. }
  302. #endregion 缓存
  303. #region IP限流
  304. if (_appConfig.RateLimit)
  305. {
  306. services.AddIpRateLimit(_configuration, cacheConfig);
  307. }
  308. #endregion IP限流
  309. //阻止NLog接收状态消息
  310. services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
  311. }
  312. public void ConfigureContainer(ContainerBuilder builder)
  313. {
  314. #region AutoFac IOC容器
  315. try
  316. {
  317. #region SingleInstance
  318. //无接口注入单例
  319. var assemblyCore = Assembly.Load("Admin.Core");
  320. var assemblyCommon = Assembly.Load("Admin.Core.Common");
  321. builder.RegisterAssemblyTypes(assemblyCore, assemblyCommon)
  322. .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null)
  323. .SingleInstance();
  324. //有接口注入单例
  325. builder.RegisterAssemblyTypes(assemblyCore, assemblyCommon)
  326. .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null)
  327. .AsImplementedInterfaces()
  328. .SingleInstance();
  329. #endregion SingleInstance
  330. #region Aop
  331. var interceptorServiceTypes = new List<Type>();
  332. if (_appConfig.Aop.Transaction)
  333. {
  334. builder.RegisterType<TransactionInterceptor>();
  335. builder.RegisterType<TransactionAsyncInterceptor>();
  336. interceptorServiceTypes.Add(typeof(TransactionInterceptor));
  337. }
  338. #endregion Aop
  339. #region Repository
  340. var assemblyRepository = Assembly.Load("Admin.Core.Repository");
  341. builder.RegisterAssemblyTypes(assemblyRepository)
  342. .AsImplementedInterfaces()
  343. .InstancePerLifetimeScope()
  344. .PropertiesAutowired();// 属性注入
  345. //泛型注入
  346. builder.RegisterGeneric(typeof(RepositoryBase<>)).As(typeof(IRepositoryBase<>)).InstancePerLifetimeScope();
  347. builder.RegisterGeneric(typeof(RepositoryBase<,>)).As(typeof(IRepositoryBase<,>)).InstancePerLifetimeScope();
  348. #endregion Repository
  349. #region Service
  350. var assemblyServices = Assembly.Load("Admin.Core.Service");
  351. builder.RegisterAssemblyTypes(assemblyServices)
  352. .AsImplementedInterfaces()
  353. .InstancePerLifetimeScope()
  354. .PropertiesAutowired()// 属性注入
  355. .InterceptedBy(interceptorServiceTypes.ToArray())
  356. .EnableInterfaceInterceptors();
  357. #endregion Service
  358. }
  359. catch (Exception ex)
  360. {
  361. throw new Exception(ex.Message + "\n" + ex.InnerException);
  362. }
  363. #endregion AutoFac IOC容器
  364. }
  365. public void Configure(IApplicationBuilder app)
  366. {
  367. #region app配置
  368. //IP限流
  369. if (_appConfig.RateLimit)
  370. {
  371. app.UseIpRateLimiting();
  372. }
  373. //跨域
  374. if (_appConfig.CorUrls?.Length > 0)
  375. {
  376. app.UseCors(DefaultCorsPolicyName);
  377. }
  378. //异常
  379. app.UseExceptionHandler("/Error");
  380. //静态文件
  381. app.UseUploadConfig();
  382. //路由
  383. app.UseRouting();
  384. //认证
  385. app.UseAuthentication();
  386. //授权
  387. app.UseAuthorization();
  388. //配置端点
  389. app.UseEndpoints(endpoints =>
  390. {
  391. endpoints.MapControllers();
  392. });
  393. #endregion app配置
  394. #region Swagger Api文档
  395. if (_env.IsDevelopment() || _appConfig.Swagger)
  396. {
  397. app.UseSwagger();
  398. app.UseSwaggerUI(c =>
  399. {
  400. typeof(ApiVersion).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
  401. {
  402. c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Admin.Core {version}");
  403. });
  404. c.RoutePrefix = "";//直接根目录访问,如果是IIS发布可以注释该语句,并打开launchSettings.launchUrl
  405. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//折叠Api
  406. //c.DefaultModelsExpandDepth(-1);//不显示Models
  407. });
  408. }
  409. #endregion Swagger Api文档
  410. }
  411. }
  412. }