1
0

Startup.cs 17 KB

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