Startup.cs 17 KB

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