0
0

Startup.cs 17 KB

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