Startup.cs 17 KB

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