Startup.cs 17 KB

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