HostApp.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. using HealthChecks.UI.Client;
  59. using Microsoft.AspNetCore.Diagnostics.HealthChecks;
  60. namespace ZhonTai.Admin.Core;
  61. /// <summary>
  62. /// 宿主应用
  63. /// </summary>
  64. public class HostApp
  65. {
  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. services.AddHealthChecks();
  162. //雪花漂移算法
  163. var idGeneratorOptions = new IdGeneratorOptions(1) { WorkerIdBitLength = 6 };
  164. _hostAppOptions?.ConfigureIdGenerator?.Invoke(idGeneratorOptions);
  165. YitIdHelper.SetIdGenerator(idGeneratorOptions);
  166. //权限处理
  167. services.AddScoped<IPermissionHandler, PermissionHandler>();
  168. // ClaimType不被更改
  169. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  170. //用户信息
  171. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  172. services.TryAddScoped<IUser, User>();
  173. //数据库配置
  174. var dbConfig = ConfigHelper.Get<DbConfig>("dbconfig", env.EnvironmentName);
  175. services.AddSingleton(dbConfig);
  176. //添加数据库
  177. if (!_hostAppOptions.CustomInitDb)
  178. {
  179. services.AddDb(env, _hostAppOptions);
  180. }
  181. //上传配置
  182. var uploadConfig = ConfigHelper.Load("uploadconfig", env.EnvironmentName, true);
  183. services.Configure<UploadConfig>(uploadConfig);
  184. //程序集
  185. Assembly[] assemblies = null;
  186. if(appConfig.AssemblyNames?.Length > 0)
  187. {
  188. assemblies = DependencyContext.Default.RuntimeLibraries
  189. .Where(a => appConfig.AssemblyNames.Contains(a.Name))
  190. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  191. }
  192. #region Mapster 映射配置
  193. services.AddScoped<IMapper>(sp => new Mapper());
  194. if(assemblies?.Length > 0)
  195. {
  196. TypeAdapterConfig.GlobalSettings.Scan(assemblies);
  197. }
  198. #endregion Mapster 映射配置
  199. #region Cors 跨域
  200. services.AddCors(options =>
  201. {
  202. options.AddPolicy(AdminConsts.RequestPolicyName, policy =>
  203. {
  204. var hasOrigins = appConfig.CorUrls?.Length > 0;
  205. if (hasOrigins)
  206. {
  207. policy.WithOrigins(appConfig.CorUrls);
  208. }
  209. else
  210. {
  211. policy.AllowAnyOrigin();
  212. }
  213. policy
  214. .AllowAnyHeader()
  215. .AllowAnyMethod();
  216. if (hasOrigins)
  217. {
  218. policy.AllowCredentials();
  219. }
  220. });
  221. //允许任何源访问Api策略,使用时在控制器或者接口上增加特性[EnableCors(AdminConsts.AllowAnyPolicyName)]
  222. options.AddPolicy(AdminConsts.AllowAnyPolicyName, policy =>
  223. {
  224. policy
  225. .AllowAnyOrigin()
  226. .AllowAnyHeader()
  227. .AllowAnyMethod();
  228. });
  229. });
  230. #endregion Cors 跨域
  231. #region 身份认证授权
  232. var jwtConfig = ConfigHelper.Get<JwtConfig>("jwtconfig", env.EnvironmentName);
  233. services.TryAddSingleton(jwtConfig);
  234. services.AddAuthentication(options =>
  235. {
  236. options.DefaultScheme = appConfig.IdentityServer.Enable ? IdentityServerAuthenticationDefaults.AuthenticationScheme : JwtBearerDefaults.AuthenticationScheme;
  237. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  238. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  239. })
  240. .AddJwtBearer(options =>
  241. {
  242. //ids4
  243. if (appConfig.IdentityServer.Enable)
  244. {
  245. options.Authority = appConfig.IdentityServer.Url;
  246. options.RequireHttpsMetadata = appConfig.IdentityServer.RequireHttpsMetadata;
  247. options.Audience = appConfig.IdentityServer.Audience;
  248. }
  249. else
  250. {
  251. options.TokenValidationParameters = new TokenValidationParameters
  252. {
  253. ValidateIssuer = true,
  254. ValidateAudience = true,
  255. ValidateLifetime = true,
  256. ValidateIssuerSigningKey = true,
  257. ValidIssuer = jwtConfig.Issuer,
  258. ValidAudience = jwtConfig.Audience,
  259. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  260. ClockSkew = TimeSpan.Zero
  261. };
  262. }
  263. })
  264. .AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  265. #endregion 身份认证授权
  266. #region Swagger Api文档
  267. if (env.IsDevelopment() || appConfig.Swagger.Enable)
  268. {
  269. services.AddSwaggerGen(options =>
  270. {
  271. appConfig.Swagger.Projects?.ForEach(project =>
  272. {
  273. options.SwaggerDoc(project.Code.ToLower(), new OpenApiInfo
  274. {
  275. Title = project.Name,
  276. Version = project.Version,
  277. Description = project.Description
  278. });
  279. });
  280. options.CustomOperationIds(apiDesc =>
  281. {
  282. var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor;
  283. var api = controllerAction.AttributeRouteInfo.Template;
  284. api = Regex.Replace(api, @"[\{\\\/\}]", "-") + "-" + apiDesc.HttpMethod.ToLower();
  285. return api.Replace("--", "-");
  286. });
  287. options.ResolveConflictingActions(apiDescription => apiDescription.First());
  288. options.CustomSchemaIds(modelType => DefaultSchemaIdSelector(modelType));
  289. //支持多分组
  290. options.DocInclusionPredicate((docName, apiDescription) =>
  291. {
  292. var nonGroup = false;
  293. var groupNames = new List<string>();
  294. var dynamicApiAttribute = apiDescription.ActionDescriptor.EndpointMetadata.FirstOrDefault(x => x is DynamicApiAttribute);
  295. if (dynamicApiAttribute != null)
  296. {
  297. var dynamicApi = dynamicApiAttribute as DynamicApiAttribute;
  298. if(dynamicApi.GroupNames?.Length > 0)
  299. {
  300. groupNames.AddRange(dynamicApi.GroupNames);
  301. }
  302. }
  303. var apiGroupAttribute = apiDescription.ActionDescriptor.EndpointMetadata.FirstOrDefault(x => x is ApiGroupAttribute);
  304. if (apiGroupAttribute != null)
  305. {
  306. var apiGroup = apiGroupAttribute as ApiGroupAttribute;
  307. if (apiGroup.GroupNames?.Length > 0)
  308. {
  309. groupNames.AddRange(apiGroup.GroupNames);
  310. }
  311. nonGroup = apiGroup.NonGroup;
  312. }
  313. return docName == apiDescription.GroupName || groupNames.Any(a => a == docName) || nonGroup;
  314. });
  315. string[] xmlFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.xml");
  316. if (xmlFiles.Length > 0)
  317. {
  318. foreach (var xmlFile in xmlFiles)
  319. {
  320. options.IncludeXmlComments(xmlFile, true);
  321. }
  322. }
  323. var server = new OpenApiServer()
  324. {
  325. Url = appConfig.Swagger.Url,
  326. Description = ""
  327. };
  328. if (appConfig.ApiUI.Footer.Enable)
  329. {
  330. server.Extensions.Add("extensions", new OpenApiObject
  331. {
  332. ["copyright"] = new OpenApiString(appConfig.ApiUI.Footer.Content)
  333. });
  334. }
  335. options.AddServer(server);
  336. if(appConfig.Swagger.EnableEnumSchemaFilter)
  337. {
  338. options.SchemaFilter<EnumSchemaFilter>();
  339. }
  340. if(appConfig.Swagger.EnableOrderTagsDocumentFilter)
  341. {
  342. options.DocumentFilter<OrderTagsDocumentFilter>();
  343. }
  344. options.OrderActionsBy(apiDesc =>
  345. {
  346. var order = 0;
  347. var objOrderAttribute = apiDesc.CustomAttributes().FirstOrDefault(x => x is OrderAttribute);
  348. if (objOrderAttribute != null)
  349. {
  350. var orderAttribute = objOrderAttribute as OrderAttribute;
  351. order = orderAttribute.Value;
  352. }
  353. return (int.MaxValue - order).ToString().PadLeft(int.MaxValue.ToString().Length, '0');
  354. });
  355. #region 添加设置Token的按钮
  356. if (appConfig.IdentityServer.Enable)
  357. {
  358. //添加Jwt验证设置
  359. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  360. {
  361. {
  362. new OpenApiSecurityScheme
  363. {
  364. Reference = new OpenApiReference
  365. {
  366. Id = "oauth2",
  367. Type = ReferenceType.SecurityScheme
  368. }
  369. },
  370. new List<string>()
  371. }
  372. });
  373. //统一认证
  374. options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
  375. {
  376. Type = SecuritySchemeType.OAuth2,
  377. Description = "oauth2登录授权",
  378. Flows = new OpenApiOAuthFlows
  379. {
  380. Implicit = new OpenApiOAuthFlow
  381. {
  382. AuthorizationUrl = new Uri($"{appConfig.IdentityServer.Url}/connect/authorize", UriKind.Absolute),
  383. TokenUrl = new Uri($"{appConfig.IdentityServer.Url}/connect/token", UriKind.Absolute),
  384. Scopes = new Dictionary<string, string>
  385. {
  386. { "admin.server.api", "admin后端api" }
  387. }
  388. }
  389. }
  390. });
  391. }
  392. else
  393. {
  394. //添加Jwt验证设置
  395. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  396. {
  397. {
  398. new OpenApiSecurityScheme
  399. {
  400. Reference = new OpenApiReference
  401. {
  402. Id = "Bearer",
  403. Type = ReferenceType.SecurityScheme
  404. }
  405. },
  406. new List<string>()
  407. }
  408. });
  409. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  410. {
  411. Description = "Value: Bearer {token}",
  412. Name = "Authorization",
  413. In = ParameterLocation.Header,
  414. Type = SecuritySchemeType.ApiKey
  415. });
  416. }
  417. #endregion 添加设置Token的按钮
  418. });
  419. }
  420. #endregion Swagger Api文档
  421. #region 操作日志
  422. if (appConfig.Log.Operation)
  423. {
  424. services.AddScoped<ILogHandler, LogHandler>();
  425. }
  426. #endregion 操作日志
  427. #region 控制器
  428. void mvcConfigure(MvcOptions options)
  429. {
  430. //options.Filters.Add<ControllerExceptionFilter>();
  431. options.Filters.Add<ValidateInputFilter>();
  432. if (appConfig.Validate.Login || appConfig.Validate.Permission)
  433. {
  434. options.Filters.Add<ValidatePermissionAttribute>();
  435. }
  436. //在具有较高的 Order 值的筛选器之前运行 before 代码
  437. //在具有较高的 Order 值的筛选器之后运行 after 代码
  438. if (appConfig.DynamicApi.FormatResult)
  439. {
  440. options.Filters.Add<FormatResultFilter>(20);
  441. }
  442. if (appConfig.Log.Operation)
  443. {
  444. options.Filters.Add<ControllerLogFilter>(10);
  445. }
  446. //禁止去除ActionAsync后缀
  447. //options.SuppressAsyncSuffixInActionNames = false;
  448. if (env.IsDevelopment() || appConfig.Swagger.Enable)
  449. {
  450. //API分组约定
  451. options.Conventions.Add(new ApiGroupConvention());
  452. }
  453. }
  454. var mvcBuilder = appConfig.AppType switch
  455. {
  456. AppType.Controllers => services.AddControllers(mvcConfigure),
  457. AppType.ControllersWithViews => services.AddControllersWithViews(mvcConfigure),
  458. AppType.MVC => services.AddMvc(mvcConfigure),
  459. _ => services.AddControllers(mvcConfigure)
  460. };
  461. if (assemblies?.Length > 0)
  462. {
  463. foreach (var assembly in assemblies)
  464. {
  465. services.AddValidatorsFromAssembly(assembly);
  466. }
  467. }
  468. services.AddFluentValidationAutoValidation();
  469. mvcBuilder.AddNewtonsoftJson(options =>
  470. {
  471. //忽略循环引用
  472. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  473. //使用驼峰 首字母小写
  474. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  475. //设置时间格式
  476. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  477. })
  478. .AddControllersAsServices();
  479. if (appConfig.Swagger.EnableJsonStringEnumConverter)
  480. mvcBuilder.AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
  481. _hostAppOptions?.ConfigureMvcBuilder?.Invoke(mvcBuilder, hostAppContext);
  482. #endregion 控制器
  483. services.AddHttpClient();
  484. _hostAppOptions?.ConfigureServices?.Invoke(hostAppContext);
  485. #region 缓存
  486. var cacheConfig = ConfigHelper.Get<CacheConfig>("cacheconfig", env.EnvironmentName);
  487. if (cacheConfig.Type == CacheType.Redis)
  488. {
  489. var redis = new RedisClient(cacheConfig.Redis.ConnectionString)
  490. {
  491. Serialize = JsonConvert.SerializeObject,
  492. Deserialize = JsonConvert.DeserializeObject
  493. };
  494. services.AddSingleton(redis);
  495. services.AddSingleton<ICacheTool, RedisCacheTool>();
  496. }
  497. else
  498. {
  499. services.AddMemoryCache();
  500. services.AddSingleton<ICacheTool, MemoryCacheTool>();
  501. }
  502. #endregion 缓存
  503. #region IP限流
  504. if (appConfig.RateLimit)
  505. {
  506. services.AddIpRateLimit(configuration, cacheConfig);
  507. }
  508. #endregion IP限流
  509. //阻止NLog接收状态消息
  510. services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
  511. //性能分析
  512. if (appConfig.MiniProfiler)
  513. {
  514. services.AddMiniProfiler();
  515. }
  516. //动态api
  517. services.AddDynamicApi(options =>
  518. {
  519. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  520. .Where(a => a.Name.EndsWith("Service"))
  521. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  522. options.AddAssemblyOptions(assemblies);
  523. options.FormatResult = appConfig.DynamicApi.FormatResult;
  524. options.FormatResultType = typeof(ResultOutput<>);
  525. _hostAppOptions?.ConfigureDynamicApi?.Invoke(options);
  526. });
  527. _hostAppOptions?.ConfigurePostServices?.Invoke(hostAppContext);
  528. }
  529. /// <summary>
  530. /// 配置中间件
  531. /// </summary>
  532. /// <param name="app"></param>
  533. /// <param name="env"></param>
  534. /// <param name="configuration"></param>
  535. /// <param name="appConfig"></param>
  536. private void ConfigureMiddleware(WebApplication app, IWebHostEnvironment env, IConfiguration configuration, AppConfig appConfig)
  537. {
  538. var hostAppMiddlewareContext = new HostAppMiddlewareContext()
  539. {
  540. App = app,
  541. Environment = env,
  542. Configuration = configuration
  543. };
  544. _hostAppOptions?.ConfigurePreMiddleware?.Invoke(hostAppMiddlewareContext);
  545. //异常处理
  546. app.UseMiddleware<ExceptionMiddleware>();
  547. //IP限流
  548. if (appConfig.RateLimit)
  549. {
  550. app.UseIpRateLimiting();
  551. }
  552. //性能分析
  553. if (appConfig.MiniProfiler)
  554. {
  555. app.UseMiniProfiler();
  556. }
  557. //静态文件
  558. app.UseDefaultFiles();
  559. app.UseStaticFiles();
  560. app.UseUploadConfig();
  561. //路由
  562. app.UseRouting();
  563. //跨域
  564. app.UseCors(AdminConsts.RequestPolicyName);
  565. //认证
  566. app.UseAuthentication();
  567. //授权
  568. app.UseAuthorization();
  569. //登录用户初始化数据权限
  570. if (appConfig.Validate.Permission)
  571. {
  572. app.Use(async (ctx, next) =>
  573. {
  574. var user = ctx.RequestServices.GetRequiredService<IUser>();
  575. if (user?.Id > 0)
  576. {
  577. var userService = ctx.RequestServices.GetRequiredService<IUserService>();
  578. await userService.GetDataPermissionAsync();
  579. }
  580. await next();
  581. });
  582. }
  583. //配置端点
  584. app.MapControllers();
  585. _hostAppOptions?.ConfigureMiddleware?.Invoke(hostAppMiddlewareContext);
  586. #region Swagger Api文档
  587. if (env.IsDevelopment() || appConfig.Swagger.Enable)
  588. {
  589. var routePrefix = appConfig.ApiUI.RoutePrefix;
  590. if (!appConfig.ApiUI.Enable && routePrefix.IsNull())
  591. {
  592. routePrefix = appConfig.Swagger.RoutePrefix;
  593. }
  594. var routePath = routePrefix.NotNull() ? $"{routePrefix}/" : "";
  595. app.UseSwagger(optoins =>
  596. {
  597. optoins.RouteTemplate = routePath + optoins.RouteTemplate;
  598. });
  599. app.UseSwaggerUI(options =>
  600. {
  601. options.RoutePrefix = appConfig.Swagger.RoutePrefix;
  602. appConfig.Swagger.Projects?.ForEach(project =>
  603. {
  604. options.SwaggerEndpoint($"/{routePath}swagger/{project.Code.ToLower()}/swagger.json", project.Name);
  605. });
  606. options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);//折叠Api
  607. //options.DefaultModelsExpandDepth(-1);//不显示Models
  608. if (appConfig.MiniProfiler)
  609. {
  610. options.InjectJavascript("/swagger/mini-profiler.js?v=4.2.22+2.0");
  611. options.InjectStylesheet("/swagger/mini-profiler.css?v=4.2.22+2.0");
  612. }
  613. });
  614. }
  615. #endregion Swagger Api文档
  616. //使用健康检查
  617. if(appConfig.HealthChecks.Enable)
  618. {
  619. app.MapHealthChecks(appConfig.HealthChecks.Path, new HealthCheckOptions()
  620. {
  621. Predicate = _ => true,
  622. ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
  623. });
  624. }
  625. _hostAppOptions?.ConfigurePostMiddleware?.Invoke(hostAppMiddlewareContext);
  626. }
  627. }