Startup.cs 13 KB

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