Startup.cs 16 KB

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