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