Startup.cs 18 KB

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