HostApp.cs 24 KB

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