Startup.cs 16 KB

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