0
0

Startup.cs 16 KB

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