0
0

Startup.cs 18 KB

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