HostApp.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. using AspNetCoreRateLimit;
  2. using Autofac;
  3. using IdentityServer4.AccessTokenValidation;
  4. using Microsoft.AspNetCore.Authentication;
  5. using Microsoft.AspNetCore.Authentication.JwtBearer;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.DependencyInjection.Extensions;
  12. using Microsoft.Extensions.Hosting;
  13. using Microsoft.Extensions.DependencyModel;
  14. using Microsoft.IdentityModel.Tokens;
  15. using Microsoft.OpenApi.Models;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Serialization;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.IdentityModel.Tokens.Jwt;
  21. using System.Linq;
  22. using System.Reflection;
  23. using System.Text;
  24. using Mapster;
  25. using Yitter.IdGenerator;
  26. using FluentValidation;
  27. using FluentValidation.AspNetCore;
  28. using ZhonTai.Admin.Core.Auth;
  29. using ZhonTai.Admin.Tools.Cache;
  30. using ZhonTai.Common.Helpers;
  31. using ZhonTai.Admin.Core.Db;
  32. using ZhonTai.Admin.Core.Extensions;
  33. using ZhonTai.Admin.Core.Filters;
  34. using ZhonTai.Admin.Core.Logs;
  35. using ZhonTai.Admin.Core.RegisterModules;
  36. using System.IO;
  37. using Microsoft.OpenApi.Any;
  38. using Microsoft.AspNetCore.Mvc.Controllers;
  39. using ZhonTai.Admin.Core.Attributes;
  40. using ZhonTai.Admin.Core.Configs;
  41. using ZhonTai.Admin.Core.Consts;
  42. using MapsterMapper;
  43. using ZhonTai.DynamicApi;
  44. using NLog.Web;
  45. using Autofac.Extensions.DependencyInjection;
  46. using Microsoft.AspNetCore.Mvc;
  47. using ZhonTai.Admin.Core.Startup;
  48. using ZhonTai.Admin.Core.Conventions;
  49. using FreeSql;
  50. using ZhonTai.Admin.Services.User;
  51. using ZhonTai.Admin.Core.Middlewares;
  52. using ZhonTai.Admin.Core.Dto;
  53. using ZhonTai.DynamicApi.Attributes;
  54. using System.Text.RegularExpressions;
  55. using Swashbuckle.AspNetCore.SwaggerGen;
  56. using System.Text.Json.Serialization;
  57. using FreeRedis;
  58. namespace ZhonTai.Admin.Core;
  59. /// <summary>
  60. /// 宿主应用
  61. /// </summary>
  62. public partial class HostApp
  63. {
  64. [GeneratedRegex("[\\{\\\\\\/\\}]")]
  65. private static partial Regex PathRegex();
  66. readonly HostAppOptions _hostAppOptions;
  67. public HostApp()
  68. {
  69. }
  70. public HostApp(HostAppOptions hostAppOptions)
  71. {
  72. _hostAppOptions = hostAppOptions;
  73. }
  74. /// <summary>
  75. /// 运行应用
  76. /// </summary>
  77. /// <param name="args"></param>
  78. public void Run(string[] args)
  79. {
  80. var builder = WebApplication.CreateBuilder(args);
  81. //使用NLog日志
  82. builder.Host.UseNLog();
  83. var services = builder.Services;
  84. var env = builder.Environment;
  85. var configuration = builder.Configuration;
  86. var configHelper = new ConfigHelper();
  87. var appConfig = ConfigHelper.Get<AppConfig>("appconfig", env.EnvironmentName) ?? new AppConfig();
  88. //添加配置
  89. builder.Configuration.AddJsonFile("./Configs/ratelimitconfig.json", optional: true, reloadOnChange: true);
  90. if (env.EnvironmentName.NotNull())
  91. {
  92. builder.Configuration.AddJsonFile($"./Configs/ratelimitconfig.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
  93. }
  94. builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
  95. if (env.EnvironmentName.NotNull())
  96. {
  97. builder.Configuration.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
  98. }
  99. var oSSConfigRoot = ConfigHelper.Load("ossconfig", env.EnvironmentName, true);
  100. services.Configure<OSSConfig>(oSSConfigRoot);
  101. //应用配置
  102. services.AddSingleton(appConfig);
  103. //使用Autofac容器
  104. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  105. //配置Autofac容器
  106. builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  107. {
  108. // 控制器注入
  109. builder.RegisterModule(new ControllerModule());
  110. // 单例注入
  111. builder.RegisterModule(new SingleInstanceModule(appConfig));
  112. // 模块注入
  113. builder.RegisterModule(new RegisterModule(appConfig));
  114. });
  115. //配置Kestrel服务器
  116. builder.WebHost.ConfigureKestrel((context, options) =>
  117. {
  118. //设置应用服务器Kestrel请求体最大为100MB
  119. options.Limits.MaxRequestBodySize = appConfig.MaxRequestBodySize;
  120. });
  121. //访问地址
  122. builder.WebHost.UseUrls(appConfig.Urls);
  123. //配置服务
  124. ConfigureServices(services, env, configuration, configHelper, appConfig);
  125. var app = builder.Build();
  126. //配置中间件
  127. ConfigureMiddleware(app, env, configuration, appConfig);
  128. app.Run();
  129. }
  130. /// <summary>
  131. /// 实体类型重命名
  132. /// </summary>
  133. /// <param name="modelType"></param>
  134. /// <returns></returns>
  135. private string DefaultSchemaIdSelector(Type modelType)
  136. {
  137. if (!modelType.IsConstructedGenericType) return modelType.Name.Replace("[]", "Array");
  138. var prefix = modelType.GetGenericArguments()
  139. .Select(DefaultSchemaIdSelector)
  140. .Aggregate((previous, current) => previous + current);
  141. return modelType.Name.Split('`').First() + prefix;
  142. }
  143. /// <summary>
  144. /// 配置服务
  145. /// </summary>
  146. /// <param name="services"></param>
  147. /// <param name="env"></param>
  148. /// <param name="configuration"></param>
  149. /// <param name="configHelper"></param>
  150. /// <param name="appConfig"></param>
  151. private void ConfigureServices(IServiceCollection services, IWebHostEnvironment env, IConfiguration configuration, ConfigHelper configHelper, AppConfig appConfig)
  152. {
  153. var hostAppContext = new HostAppContext()
  154. {
  155. Services = services,
  156. Environment = env,
  157. Configuration = configuration
  158. };
  159. _hostAppOptions?.ConfigurePreServices?.Invoke(hostAppContext);
  160. //雪花漂移算法
  161. var idGeneratorOptions = new IdGeneratorOptions(1) { WorkerIdBitLength = 6 };
  162. _hostAppOptions?.ConfigureIdGenerator?.Invoke(idGeneratorOptions);
  163. YitIdHelper.SetIdGenerator(idGeneratorOptions);
  164. //权限处理
  165. services.AddScoped<IPermissionHandler, PermissionHandler>();
  166. // ClaimType不被更改
  167. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  168. //用户信息
  169. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  170. services.TryAddScoped<IUser, User>();
  171. //数据库配置
  172. var dbConfig = ConfigHelper.Get<DbConfig>("dbconfig", env.EnvironmentName);
  173. services.AddSingleton(dbConfig);
  174. //添加数据库
  175. if (!_hostAppOptions.CustomInitDb)
  176. {
  177. services.AddDb(env, _hostAppOptions);
  178. }
  179. //上传配置
  180. var uploadConfig = ConfigHelper.Load("uploadconfig", env.EnvironmentName, true);
  181. services.Configure<UploadConfig>(uploadConfig);
  182. //程序集
  183. Assembly[] assemblies = null;
  184. if(appConfig.AssemblyNames?.Length > 0)
  185. {
  186. assemblies = DependencyContext.Default.RuntimeLibraries
  187. .Where(a => appConfig.AssemblyNames.Contains(a.Name))
  188. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  189. }
  190. #region Mapster 映射配置
  191. services.AddScoped<IMapper>(sp => new Mapper());
  192. if(assemblies?.Length > 0)
  193. {
  194. TypeAdapterConfig.GlobalSettings.Scan(assemblies);
  195. }
  196. #endregion Mapster 映射配置
  197. #region Cors 跨域
  198. services.AddCors(options =>
  199. {
  200. options.AddPolicy(AdminConsts.RequestPolicyName, policy =>
  201. {
  202. var hasOrigins = appConfig.CorUrls?.Length > 0;
  203. if (hasOrigins)
  204. {
  205. policy.WithOrigins(appConfig.CorUrls);
  206. }
  207. else
  208. {
  209. policy.AllowAnyOrigin();
  210. }
  211. policy
  212. .AllowAnyHeader()
  213. .AllowAnyMethod();
  214. if (hasOrigins)
  215. {
  216. policy.AllowCredentials();
  217. }
  218. });
  219. //允许任何源访问Api策略,使用时在控制器或者接口上增加特性[EnableCors(AdminConsts.AllowAnyPolicyName)]
  220. options.AddPolicy(AdminConsts.AllowAnyPolicyName, policy =>
  221. {
  222. policy
  223. .AllowAnyOrigin()
  224. .AllowAnyHeader()
  225. .AllowAnyMethod();
  226. });
  227. });
  228. #endregion Cors 跨域
  229. #region 身份认证授权
  230. var jwtConfig = ConfigHelper.Get<JwtConfig>("jwtconfig", env.EnvironmentName);
  231. services.TryAddSingleton(jwtConfig);
  232. services.AddAuthentication(options =>
  233. {
  234. options.DefaultScheme = appConfig.IdentityServer.Enable ? IdentityServerAuthenticationDefaults.AuthenticationScheme : JwtBearerDefaults.AuthenticationScheme;
  235. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  236. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  237. })
  238. .AddJwtBearer(options =>
  239. {
  240. //ids4
  241. if (appConfig.IdentityServer.Enable)
  242. {
  243. options.Authority = appConfig.IdentityServer.Url;
  244. options.RequireHttpsMetadata = appConfig.IdentityServer.RequireHttpsMetadata;
  245. options.Audience = appConfig.IdentityServer.Audience;
  246. }
  247. else
  248. {
  249. options.TokenValidationParameters = new TokenValidationParameters
  250. {
  251. ValidateIssuer = true,
  252. ValidateAudience = true,
  253. ValidateLifetime = true,
  254. ValidateIssuerSigningKey = true,
  255. ValidIssuer = jwtConfig.Issuer,
  256. ValidAudience = jwtConfig.Audience,
  257. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  258. ClockSkew = TimeSpan.Zero
  259. };
  260. }
  261. })
  262. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  263. #endregion 身份认证授权
  264. #region Swagger Api文档
  265. if (env.IsDevelopment() || appConfig.Swagger.Enable)
  266. {
  267. services.AddSwaggerGen(options =>
  268. {
  269. appConfig.Swagger.Projects?.ForEach(project =>
  270. {
  271. options.SwaggerDoc(project.Code.ToLower(), new OpenApiInfo
  272. {
  273. Title = project.Name,
  274. Version = project.Version,
  275. Description = project.Description
  276. });
  277. });
  278. options.CustomOperationIds(apiDesc =>
  279. {
  280. var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor;
  281. var api = controllerAction.AttributeRouteInfo.Template;
  282. api = PathRegex().Replace(api, "-") + "-" + apiDesc.HttpMethod.ToLower();
  283. return api.Replace("--", "-");
  284. });
  285. options.ResolveConflictingActions(apiDescription => apiDescription.First());
  286. options.CustomSchemaIds(modelType => DefaultSchemaIdSelector(modelType));
  287. //支持多分组
  288. options.DocInclusionPredicate((docName, apiDescription) =>
  289. {
  290. var nonGroup = false;
  291. var groupNames = new List<string>();
  292. var dynamicApiAttribute = apiDescription.ActionDescriptor.EndpointMetadata.FirstOrDefault(x => x is DynamicApiAttribute);
  293. if (dynamicApiAttribute != null)
  294. {
  295. var dynamicApi = dynamicApiAttribute as DynamicApiAttribute;
  296. if(dynamicApi.GroupNames?.Length > 0)
  297. {
  298. groupNames.AddRange(dynamicApi.GroupNames);
  299. }
  300. }
  301. var apiGroupAttribute = apiDescription.ActionDescriptor.EndpointMetadata.FirstOrDefault(x => x is ApiGroupAttribute);
  302. if (apiGroupAttribute != null)
  303. {
  304. var apiGroup = apiGroupAttribute as ApiGroupAttribute;
  305. if (apiGroup.GroupNames?.Length > 0)
  306. {
  307. groupNames.AddRange(apiGroup.GroupNames);
  308. }
  309. nonGroup = apiGroup.NonGroup;
  310. }
  311. return docName == apiDescription.GroupName || groupNames.Any(a => a == docName) || nonGroup;
  312. });
  313. string[] xmlFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.xml");
  314. if (xmlFiles.Length > 0)
  315. {
  316. foreach (var xmlFile in xmlFiles)
  317. {
  318. options.IncludeXmlComments(xmlFile, true);
  319. }
  320. }
  321. var server = new OpenApiServer()
  322. {
  323. Url = appConfig.Swagger.Url,
  324. Description = ""
  325. };
  326. if (appConfig.ApiUI.Footer.Enable)
  327. {
  328. server.Extensions.Add("extensions", new OpenApiObject
  329. {
  330. ["copyright"] = new OpenApiString(appConfig.ApiUI.Footer.Content)
  331. });
  332. }
  333. options.AddServer(server);
  334. if(appConfig.Swagger.EnableEnumSchemaFilter)
  335. {
  336. options.SchemaFilter<EnumSchemaFilter>();
  337. }
  338. if(appConfig.Swagger.EnableOrderTagsDocumentFilter)
  339. {
  340. options.DocumentFilter<OrderTagsDocumentFilter>();
  341. }
  342. options.OrderActionsBy(apiDesc =>
  343. {
  344. var order = 0;
  345. var objOrderAttribute = apiDesc.CustomAttributes().FirstOrDefault(x => x is OrderAttribute);
  346. if (objOrderAttribute != null)
  347. {
  348. var orderAttribute = objOrderAttribute as OrderAttribute;
  349. order = orderAttribute.Value;
  350. }
  351. return (int.MaxValue - order).ToString().PadLeft(int.MaxValue.ToString().Length, '0');
  352. });
  353. #region 添加设置Token的按钮
  354. if (appConfig.IdentityServer.Enable)
  355. {
  356. //添加Jwt验证设置
  357. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  358. {
  359. {
  360. new OpenApiSecurityScheme
  361. {
  362. Reference = new OpenApiReference
  363. {
  364. Id = "oauth2",
  365. Type = ReferenceType.SecurityScheme
  366. }
  367. },
  368. new List<string>()
  369. }
  370. });
  371. //统一认证
  372. options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
  373. {
  374. Type = SecuritySchemeType.OAuth2,
  375. Description = "oauth2登录授权",
  376. Flows = new OpenApiOAuthFlows
  377. {
  378. Implicit = new OpenApiOAuthFlow
  379. {
  380. AuthorizationUrl = new Uri($"{appConfig.IdentityServer.Url}/connect/authorize", UriKind.Absolute),
  381. TokenUrl = new Uri($"{appConfig.IdentityServer.Url}/connect/token", UriKind.Absolute),
  382. Scopes = new Dictionary<string, string>
  383. {
  384. { "admin.server.api", "admin后端api" }
  385. }
  386. }
  387. }
  388. });
  389. }
  390. else
  391. {
  392. //添加Jwt验证设置
  393. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  394. {
  395. {
  396. new OpenApiSecurityScheme
  397. {
  398. Reference = new OpenApiReference
  399. {
  400. Id = "Bearer",
  401. Type = ReferenceType.SecurityScheme
  402. }
  403. },
  404. new List<string>()
  405. }
  406. });
  407. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  408. {
  409. Description = "Value: Bearer {token}",
  410. Name = "Authorization",
  411. In = ParameterLocation.Header,
  412. Type = SecuritySchemeType.ApiKey
  413. });
  414. }
  415. #endregion 添加设置Token的按钮
  416. });
  417. }
  418. #endregion Swagger Api文档
  419. #region 操作日志
  420. if (appConfig.Log.Operation)
  421. {
  422. services.AddScoped<ILogHandler, LogHandler>();
  423. }
  424. #endregion 操作日志
  425. #region 控制器
  426. void mvcConfigure(MvcOptions options)
  427. {
  428. //options.Filters.Add<ControllerExceptionFilter>();
  429. options.Filters.Add<ValidateInputFilter>();
  430. if (appConfig.Validate.Login || appConfig.Validate.Permission)
  431. {
  432. options.Filters.Add<ValidatePermissionAttribute>();
  433. }
  434. //在具有较高的 Order 值的筛选器之前运行 before 代码
  435. //在具有较高的 Order 值的筛选器之后运行 after 代码
  436. if (appConfig.DynamicApi.FormatResult)
  437. {
  438. options.Filters.Add<FormatResultFilter>(20);
  439. }
  440. if (appConfig.Log.Operation)
  441. {
  442. options.Filters.Add<ControllerLogFilter>(10);
  443. }
  444. //禁止去除ActionAsync后缀
  445. //options.SuppressAsyncSuffixInActionNames = false;
  446. if (env.IsDevelopment() || appConfig.Swagger.Enable)
  447. {
  448. //API分组约定
  449. options.Conventions.Add(new ApiGroupConvention());
  450. }
  451. }
  452. var mvcBuilder = appConfig.AppType switch
  453. {
  454. AppType.Controllers => services.AddControllers(mvcConfigure),
  455. AppType.ControllersWithViews => services.AddControllersWithViews(mvcConfigure),
  456. AppType.MVC => services.AddMvc(mvcConfigure),
  457. _ => services.AddControllers(mvcConfigure)
  458. };
  459. if (assemblies?.Length > 0)
  460. {
  461. foreach (var assembly in assemblies)
  462. {
  463. services.AddValidatorsFromAssembly(assembly);
  464. }
  465. }
  466. services.AddFluentValidationAutoValidation();
  467. mvcBuilder.AddNewtonsoftJson(options =>
  468. {
  469. //忽略循环引用
  470. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  471. //使用驼峰 首字母小写
  472. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  473. //设置时间格式
  474. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  475. })
  476. .AddControllersAsServices();
  477. if (appConfig.Swagger.EnableJsonStringEnumConverter)
  478. mvcBuilder.AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
  479. _hostAppOptions?.ConfigureMvcBuilder?.Invoke(mvcBuilder, hostAppContext);
  480. #endregion 控制器
  481. services.AddHttpClient();
  482. _hostAppOptions?.ConfigureServices?.Invoke(hostAppContext);
  483. #region 缓存
  484. var cacheConfig = ConfigHelper.Get<CacheConfig>("cacheconfig", env.EnvironmentName);
  485. if (cacheConfig.Type == CacheType.Redis)
  486. {
  487. var redis = new RedisClient(cacheConfig.Redis.ConnectionString);
  488. redis.Serialize = JsonConvert.SerializeObject;
  489. redis.Deserialize = JsonConvert.DeserializeObject;
  490. services.AddSingleton(redis);
  491. services.AddSingleton<ICacheTool, RedisCacheTool>();
  492. }
  493. else
  494. {
  495. services.AddMemoryCache();
  496. services.AddSingleton<ICacheTool, MemoryCacheTool>();
  497. }
  498. #endregion 缓存
  499. #region IP限流
  500. if (appConfig.RateLimit)
  501. {
  502. services.AddIpRateLimit(configuration, cacheConfig);
  503. }
  504. #endregion IP限流
  505. //阻止NLog接收状态消息
  506. services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
  507. //性能分析
  508. if (appConfig.MiniProfiler)
  509. {
  510. services.AddMiniProfiler();
  511. }
  512. //动态api
  513. services.AddDynamicApi(options =>
  514. {
  515. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  516. .Where(a => a.Name.EndsWith("Service"))
  517. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  518. options.AddAssemblyOptions(assemblies);
  519. options.FormatResult = appConfig.DynamicApi.FormatResult;
  520. options.FormatResultType = typeof(ResultOutput<>);
  521. _hostAppOptions?.ConfigureDynamicApi?.Invoke(options);
  522. });
  523. _hostAppOptions?.ConfigurePostServices?.Invoke(hostAppContext);
  524. }
  525. /// <summary>
  526. /// 配置中间件
  527. /// </summary>
  528. /// <param name="app"></param>
  529. /// <param name="env"></param>
  530. /// <param name="configuration"></param>
  531. /// <param name="appConfig"></param>
  532. private void ConfigureMiddleware(WebApplication app, IWebHostEnvironment env, IConfiguration configuration, AppConfig appConfig)
  533. {
  534. var hostAppMiddlewareContext = new HostAppMiddlewareContext()
  535. {
  536. App = app,
  537. Environment = env,
  538. Configuration = configuration
  539. };
  540. _hostAppOptions?.ConfigurePreMiddleware?.Invoke(hostAppMiddlewareContext);
  541. //异常处理
  542. app.UseMiddleware<ExceptionMiddleware>();
  543. //IP限流
  544. if (appConfig.RateLimit)
  545. {
  546. app.UseIpRateLimiting();
  547. }
  548. //性能分析
  549. if (appConfig.MiniProfiler)
  550. {
  551. app.UseMiniProfiler();
  552. }
  553. //静态文件
  554. app.UseDefaultFiles();
  555. app.UseStaticFiles();
  556. app.UseUploadConfig();
  557. //路由
  558. app.UseRouting();
  559. //跨域
  560. app.UseCors(AdminConsts.RequestPolicyName);
  561. //认证
  562. app.UseAuthentication();
  563. //授权
  564. app.UseAuthorization();
  565. //登录用户初始化数据权限
  566. if (appConfig.Validate.Permission)
  567. {
  568. app.Use(async (ctx, next) =>
  569. {
  570. var user = ctx.RequestServices.GetRequiredService<IUser>();
  571. if (user?.Id > 0)
  572. {
  573. var userService = ctx.RequestServices.GetRequiredService<IUserService>();
  574. await userService.GetDataPermissionAsync();
  575. }
  576. await next();
  577. });
  578. }
  579. //配置端点
  580. app.MapControllers();
  581. _hostAppOptions?.ConfigureMiddleware?.Invoke(hostAppMiddlewareContext);
  582. #region Swagger Api文档
  583. if (env.IsDevelopment() || appConfig.Swagger.Enable)
  584. {
  585. var routePrefix = appConfig.ApiUI.RoutePrefix;
  586. if (!appConfig.ApiUI.Enable && routePrefix.IsNull())
  587. {
  588. routePrefix = appConfig.Swagger.RoutePrefix;
  589. }
  590. var routePath = routePrefix.NotNull() ? $"{routePrefix}/" : "";
  591. app.UseSwagger(optoins =>
  592. {
  593. optoins.RouteTemplate = routePath + optoins.RouteTemplate;
  594. });
  595. app.UseSwaggerUI(options =>
  596. {
  597. options.RoutePrefix = appConfig.Swagger.RoutePrefix;
  598. appConfig.Swagger.Projects?.ForEach(project =>
  599. {
  600. options.SwaggerEndpoint($"/{routePath}swagger/{project.Code.ToLower()}/swagger.json", project.Name);
  601. });
  602. options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//折叠Api
  603. //options.DefaultModelsExpandDepth(-1);//不显示Models
  604. if (appConfig.MiniProfiler)
  605. {
  606. options.InjectJavascript("/swagger/mini-profiler.js?v=4.2.22+2.0");
  607. options.InjectStylesheet("/swagger/mini-profiler.css?v=4.2.22+2.0");
  608. }
  609. });
  610. }
  611. #endregion Swagger Api文档
  612. _hostAppOptions?.ConfigurePostMiddleware?.Invoke(hostAppMiddlewareContext);
  613. }
  614. }