0
0

Startup.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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.CorUrls)
  77. .AllowAnyHeader()
  78. .AllowAnyMethod()
  79. .AllowCredentials();
  80. });
  81. /*
  82. //浏览器会发起2次请求,使用OPTIONS发起预检请求,第二次才是api异步请求
  83. c.AddPolicy("All", policy =>
  84. {
  85. policy
  86. .AllowAnyOrigin()
  87. .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
  88. .AllowAnyHeader()
  89. .AllowAnyMethod()
  90. .AllowCredentials();
  91. });
  92. */
  93. });
  94. #endregion
  95. #region Swagger Api文档
  96. if (_env.IsDevelopment() || _appConfig.Swagger)
  97. {
  98. services.AddSwaggerGen(c =>
  99. {
  100. typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
  101. {
  102. c.SwaggerDoc(version, new OpenApiInfo
  103. {
  104. Version = version,
  105. Title = "Admin.Core"
  106. });
  107. //c.OrderActionsBy(o => o.RelativePath);
  108. });
  109. var xmlPath = Path.Combine(basePath, "Admin.Core.xml");
  110. c.IncludeXmlComments(xmlPath, true);
  111. var xmlCommonPath = Path.Combine(basePath, "Admin.Core.Common.xml");
  112. c.IncludeXmlComments(xmlCommonPath, true);
  113. var xmlModelPath = Path.Combine(basePath, "Admin.Core.Model.xml");
  114. c.IncludeXmlComments(xmlModelPath);
  115. var xmlServicesPath = Path.Combine(basePath, "Admin.Core.Service.xml");
  116. c.IncludeXmlComments(xmlServicesPath);
  117. //添加设置Token的按钮
  118. c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  119. {
  120. Description = "Value: Bearer {token}",
  121. Name = "Authorization",
  122. In = ParameterLocation.Header,
  123. Type = SecuritySchemeType.ApiKey,
  124. Scheme = "Bearer"
  125. });
  126. //添加Jwt验证设置
  127. c.AddSecurityRequirement(new OpenApiSecurityRequirement()
  128. {
  129. {
  130. new OpenApiSecurityScheme
  131. {
  132. Reference = new OpenApiReference
  133. {
  134. Type = ReferenceType.SecurityScheme,
  135. Id = "Bearer"
  136. },
  137. Scheme = "oauth2",
  138. Name = "Bearer",
  139. In = ParameterLocation.Header,
  140. },
  141. new List<string>()
  142. }
  143. });
  144. });
  145. }
  146. #endregion
  147. #region Jwt身份认证
  148. var jwtConfig = _configHelper.Get<JwtConfig>("jwtconfig", _env.EnvironmentName);
  149. services.TryAddSingleton(jwtConfig);
  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. #endregion
  172. #region 操作日志
  173. if (_appConfig.Log.Operation)
  174. {
  175. services.AddSingleton<ILogHandler, LogHandler>();
  176. }
  177. #endregion
  178. #region 控制器
  179. services.AddControllers(options =>
  180. {
  181. options.Filters.Add<AdminExceptionFilter>();
  182. if (_appConfig.Log.Operation)
  183. {
  184. options.Filters.Add<LogActionFilter>();
  185. }
  186. //禁止去除ActionAsync后缀
  187. options.SuppressAsyncSuffixInActionNames = false;
  188. })
  189. //.AddFluentValidation(config =>
  190. //{
  191. // var assembly = Assembly.LoadFrom(Path.Combine(basePath, "Admin.Core.dll"));
  192. // config.RegisterValidatorsFromAssembly(assembly);
  193. //})
  194. .AddNewtonsoftJson(options =>
  195. {
  196. //忽略循环引用
  197. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  198. //使用驼峰 首字母小写
  199. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  200. //设置时间格式
  201. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  202. });
  203. #endregion
  204. #region 缓存
  205. var cacheConfig = _configHelper.Get<CacheConfig>("cacheconfig", _env.EnvironmentName);
  206. if (cacheConfig.Type == CacheType.Redis)
  207. {
  208. var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
  209. RedisHelper.Initialization(csredis);
  210. services.AddSingleton<ICache, RedisCache>();
  211. }
  212. else
  213. {
  214. services.AddMemoryCache();
  215. services.AddSingleton<ICache, MemoryCache>();
  216. }
  217. #endregion
  218. #region IP限流
  219. if (_appConfig.RateLimit)
  220. {
  221. services.AddIpRateLimit(_configuration, cacheConfig);
  222. }
  223. #endregion
  224. //阻止NLog接收状态消息
  225. services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
  226. }
  227. public void ConfigureContainer(ContainerBuilder builder)
  228. {
  229. #region AutoFac IOC容器
  230. try
  231. {
  232. #region SingleInstance
  233. //无接口注入单例
  234. var assemblyCore = Assembly.Load("Admin.Core");
  235. var assemblyCommon = Assembly.Load("Admin.Core.Common");
  236. builder.RegisterAssemblyTypes(assemblyCore, assemblyCommon)
  237. .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null)
  238. .SingleInstance();
  239. //有接口注入单例
  240. builder.RegisterAssemblyTypes(assemblyCore, assemblyCommon)
  241. .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null)
  242. .AsImplementedInterfaces()
  243. .SingleInstance();
  244. #endregion
  245. #region Aop
  246. var interceptorServiceTypes = new List<Type>();
  247. if (_appConfig.Aop.Transaction)
  248. {
  249. builder.RegisterType<TransactionInterceptor>();
  250. interceptorServiceTypes.Add(typeof(TransactionInterceptor));
  251. }
  252. #endregion
  253. #region Repository
  254. var assemblyRepository = Assembly.Load("Admin.Core.Repository");
  255. builder.RegisterAssemblyTypes(assemblyRepository)
  256. .AsImplementedInterfaces()
  257. .InstancePerDependency();
  258. #endregion
  259. #region Service
  260. var assemblyServices = Assembly.Load("Admin.Core.Service");
  261. builder.RegisterAssemblyTypes(assemblyServices)
  262. .AsImplementedInterfaces()
  263. .InstancePerDependency()
  264. .EnableInterfaceInterceptors()
  265. .InterceptedBy(interceptorServiceTypes.ToArray());
  266. #endregion
  267. }
  268. catch (Exception ex)
  269. {
  270. throw new Exception(ex.Message + "\n" + ex.InnerException);
  271. }
  272. #endregion
  273. }
  274. public void Configure(IApplicationBuilder app)
  275. {
  276. //启动事件
  277. //, IHostApplicationLifetime lifetime
  278. //lifetime.ApplicationStarted.Register(() =>
  279. //{
  280. // Console.WriteLine($"{_appConfig.Urls}\r\n");
  281. //});
  282. #region app配置
  283. //IP限流
  284. if (_appConfig.RateLimit)
  285. {
  286. app.UseIpRateLimiting();
  287. }
  288. //异常
  289. app.UseExceptionHandler("/Error");
  290. //静态文件
  291. app.UseUploadConfig();
  292. //路由
  293. app.UseRouting();
  294. //跨域
  295. app.UseCors("Limit");
  296. //认证
  297. app.UseAuthentication();
  298. //授权
  299. app.UseAuthorization();
  300. //配置端点
  301. app.UseEndpoints(endpoints =>
  302. {
  303. endpoints.MapControllers();
  304. });
  305. #endregion
  306. #region Swagger Api文档
  307. if (_env.IsDevelopment() || _appConfig.Swagger)
  308. {
  309. app.UseSwagger();
  310. app.UseSwaggerUI(c =>
  311. {
  312. typeof(ApiVersion).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
  313. {
  314. c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Admin.Core {version}");
  315. });
  316. c.RoutePrefix = "";//直接根目录访问,如果是IIS发布可以注释该语句,并打开launchSettings.launchUrl
  317. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//折叠Api
  318. //c.DefaultModelsExpandDepth(-1);//不显示Models
  319. });
  320. }
  321. #endregion
  322. }
  323. }
  324. }