1
0

Startup.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 Microsoft.Extensions.PlatformAbstractions;
  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.Common.Auth;
  28. using Admin.Core.Auth;
  29. using Admin.Core.Enums;
  30. using Admin.Core.Filters;
  31. using Admin.Core.Db;
  32. using Admin.Core.Common.Cache;
  33. using PermissionHandler = Admin.Core.Auth.PermissionHandler;
  34. using Admin.Core.Aop;
  35. namespace Admin.Core
  36. {
  37. public class Startup
  38. {
  39. private readonly IHostEnvironment _env;
  40. private readonly AppConfig _appConfig;
  41. private static string basePath => PlatformServices.Default.Application.ApplicationBasePath;
  42. public Startup(IWebHostEnvironment env)
  43. {
  44. _env = env;
  45. _appConfig = new ConfigHelper().Get<AppConfig>("appconfig",env.EnvironmentName) ?? new AppConfig();
  46. }
  47. public void ConfigureServices(IServiceCollection services)
  48. {
  49. #region AutoMapper 自动映射
  50. var ServiceDll = Path.Combine(basePath, "Admin.Core.Service.dll");
  51. var serviceAssembly = Assembly.LoadFrom(ServiceDll);
  52. services.AddAutoMapper(serviceAssembly);
  53. #endregion
  54. #region Cors 跨域
  55. services.AddCors(c =>
  56. {
  57. c.AddPolicy("Limit", policy =>
  58. {
  59. policy
  60. .WithOrigins(_appConfig.Urls)
  61. .AllowAnyHeader()
  62. .AllowAnyMethod();
  63. });
  64. });
  65. #endregion
  66. #region Swagger Api文档
  67. if (_env.IsDevelopment() || _appConfig.Swagger)
  68. {
  69. services.AddSwaggerGen(c =>
  70. {
  71. typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
  72. {
  73. c.SwaggerDoc(version, new OpenApiInfo
  74. {
  75. Version = version,
  76. Title = "Admin.Core"
  77. });
  78. //c.OrderActionsBy(o => o.RelativePath);
  79. });
  80. var xmlModelPath = Path.Combine(basePath, "Admin.Core.Model.xml");
  81. c.IncludeXmlComments(xmlModelPath);
  82. var xmlPath = Path.Combine(basePath, "Admin.Core.xml");
  83. c.IncludeXmlComments(xmlPath, true);
  84. var xmlServicesPath = Path.Combine(basePath, "Admin.Core.Service.xml");
  85. c.IncludeXmlComments(xmlServicesPath);
  86. //添加设置Token的按钮
  87. c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  88. {
  89. Description = "Value: Bearer {token}",
  90. Name = "Authorization",
  91. In = ParameterLocation.Header,
  92. Type = SecuritySchemeType.ApiKey,
  93. Scheme = "Bearer"
  94. });
  95. //添加Jwt验证设置
  96. c.AddSecurityRequirement(new OpenApiSecurityRequirement()
  97. {
  98. {
  99. new OpenApiSecurityScheme
  100. {
  101. Reference = new OpenApiReference
  102. {
  103. Type = ReferenceType.SecurityScheme,
  104. Id = "Bearer"
  105. },
  106. Scheme = "oauth2",
  107. Name = "Bearer",
  108. In = ParameterLocation.Header,
  109. },
  110. new List<string>()
  111. }
  112. });
  113. });
  114. }
  115. #endregion
  116. #region Jwt身份认证
  117. var jwtConfig = new ConfigHelper().Get<JwtConfig>("jwtconfig", _env.EnvironmentName);
  118. services.TryAddSingleton(jwtConfig);
  119. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  120. services.TryAddSingleton<IUser, User>();
  121. services.TryAddSingleton<IUserToken, UserToken>();
  122. services.AddScoped<IPermissionHandler, PermissionHandler>();
  123. services.AddAuthentication(options =>
  124. {
  125. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  126. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  127. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  128. })
  129. .AddJwtBearer(options =>
  130. {
  131. options.TokenValidationParameters = new TokenValidationParameters
  132. {
  133. ValidateIssuer = true,
  134. ValidateAudience = true,
  135. ValidateLifetime = true,
  136. ValidateIssuerSigningKey = true,
  137. ValidIssuer = jwtConfig.Issuer,
  138. ValidAudience = jwtConfig.Audience,
  139. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  140. ClockSkew = TimeSpan.Zero
  141. };
  142. })
  143. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { }); ;
  144. #endregion
  145. #region 控制器
  146. services.AddControllers(options =>
  147. {
  148. options.Filters.Add(typeof(GlobalExceptionFilter));
  149. })
  150. //.AddFluentValidation(config =>
  151. //{
  152. // var assembly = Assembly.LoadFrom(Path.Combine(basePath, "Admin.Core.dll"));
  153. // config.RegisterValidatorsFromAssembly(assembly);
  154. //})
  155. .AddNewtonsoftJson(options =>
  156. {
  157. //忽略循环引用
  158. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  159. //使用驼峰 首字母小写
  160. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  161. //设置时间格式
  162. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  163. });
  164. #endregion
  165. //数据库
  166. services.AddDb(_env);
  167. #region 缓存
  168. var cacheConfig = new ConfigHelper().Get<CacheConfig>("cacheconfig", _env.EnvironmentName);
  169. if(cacheConfig.Type == CacheType.Redis)
  170. {
  171. var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
  172. RedisHelper.Initialization(csredis);
  173. services.AddSingleton<ICache, RedisCache>();
  174. }
  175. else
  176. {
  177. services.AddMemoryCache();
  178. services.AddSingleton<ICache, MemoryCache>();
  179. }
  180. #endregion
  181. //阻止NLog接收状态消息
  182. services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
  183. }
  184. public void ConfigureContainer(ContainerBuilder builder)
  185. {
  186. #region AutoFac IOC容器
  187. try
  188. {
  189. #region Aop
  190. var interceptorServiceTypes = new List<Type>();
  191. if (_appConfig.Aop.Transaction)
  192. {
  193. builder.RegisterType<TransactionInterceptor>();
  194. interceptorServiceTypes.Add(typeof(TransactionInterceptor));
  195. }
  196. #endregion
  197. #region Service
  198. var servicesDllFile = Path.Combine(basePath, "Admin.Core.Service.dll");
  199. var assemblysServices = Assembly.LoadFrom(servicesDllFile);
  200. builder.RegisterAssemblyTypes(assemblysServices)
  201. .AsImplementedInterfaces()
  202. .InstancePerLifetimeScope()
  203. .EnableInterfaceInterceptors()
  204. .InterceptedBy(interceptorServiceTypes.ToArray());
  205. #endregion
  206. #region Repository
  207. var repositoryDllFile = Path.Combine(basePath, "Admin.Core.Repository.dll");
  208. var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
  209. builder.RegisterAssemblyTypes(assemblysRepository)
  210. .AsImplementedInterfaces();
  211. #endregion
  212. }
  213. catch (Exception ex)
  214. {
  215. throw new Exception(ex.Message + "\n" + ex.InnerException);
  216. }
  217. #endregion
  218. }
  219. public void Configure(IApplicationBuilder app, IHostEnvironment env)
  220. {
  221. #region app配置
  222. //异常
  223. if (env.IsDevelopment())
  224. {
  225. app.UseDeveloperExceptionPage();
  226. }
  227. else
  228. {
  229. app.UseExceptionHandler("/Error");
  230. }
  231. //静态文件
  232. app.UseStaticFiles();
  233. //路由
  234. app.UseRouting();
  235. //跨域
  236. app.UseCors("Limit");
  237. //认证
  238. app.UseAuthentication();
  239. //授权
  240. app.UseAuthorization();
  241. //配置端点
  242. app.UseEndpoints(endpoints =>
  243. {
  244. endpoints.MapControllers();
  245. });
  246. #endregion
  247. #region Swagger Api文档
  248. if (_env.IsDevelopment() || _appConfig.Swagger)
  249. {
  250. app.UseSwagger();
  251. app.UseSwaggerUI(c =>
  252. {
  253. typeof(ApiVersion).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
  254. {
  255. c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Admin.Core {version}");
  256. });
  257. c.RoutePrefix = "";//直接根目录访问
  258. });
  259. }
  260. #endregion
  261. }
  262. }
  263. }