Startup.cs 12 KB

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