From b699762c1b227a92f9975fc12a21a4ec5bef80f0 Mon Sep 17 00:00:00 2001 From: KarlsEcho <1059017311@qq.com> Date: Sun, 26 Oct 2025 15:07:13 +0800 Subject: [PATCH] =?UTF-8?q?upd:=E5=9C=A8swagger=E9=87=8C=E9=9D=A2=E8=81=9A?= =?UTF-8?q?=E5=90=88=E4=BA=86Swagger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../YarpSwaggerUIBuilderExtensions.cs | 47 +++++++++++++++++++ gateways/KonSoft.InternalGateway/Program.cs | 2 + 2 files changed, 49 insertions(+) create mode 100644 gateways/KonSoft.InternalGateway/Extensions/YarpSwaggerUIBuilderExtensions.cs diff --git a/gateways/KonSoft.InternalGateway/Extensions/YarpSwaggerUIBuilderExtensions.cs b/gateways/KonSoft.InternalGateway/Extensions/YarpSwaggerUIBuilderExtensions.cs new file mode 100644 index 0000000..1fd28ff --- /dev/null +++ b/gateways/KonSoft.InternalGateway/Extensions/YarpSwaggerUIBuilderExtensions.cs @@ -0,0 +1,47 @@ +using Yarp.ReverseProxy.Configuration; +namespace KonSoft.InternalGateway.Extensions +{ + public static class YarpSwaggerUIBuilderExtensions + { + public static IApplicationBuilder UseSwaggerUIWithYarp(this IApplicationBuilder app) + { + var serviceProvider = app.ApplicationServices; + + app.UseSwagger(); + app.UseSwaggerUI(options => + { + var configuration = serviceProvider.GetRequiredService(); + var logger = serviceProvider.GetRequiredService>(); + var proxyConfigProvider = serviceProvider.GetRequiredService(); + var yarpConfig = proxyConfigProvider.GetConfig(); + + var routedClusters = yarpConfig.Clusters + .SelectMany(t => t.Destinations, + (clusterId, destination) => new { clusterId.ClusterId, destination.Value }); + + var groupedClusters = routedClusters + .GroupBy(q => q.Value.Address) + .Select(t => t.First()) + .Distinct() + .ToList(); + + foreach (var clusterGroup in groupedClusters) + { + var routeConfig = yarpConfig.Routes.FirstOrDefault(q => + q.ClusterId == clusterGroup.ClusterId); + if (routeConfig == null) + { + logger.LogWarning($"Swagger UI: Couldn't find route configuration for {clusterGroup.ClusterId}..."); + continue; + } + + options.SwaggerEndpoint($"{clusterGroup.Value.Address}/swagger/v1/swagger.json", $"{routeConfig.RouteId} API"); + options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]); + options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]); + } + }); + + return app; + } + } +} diff --git a/gateways/KonSoft.InternalGateway/Program.cs b/gateways/KonSoft.InternalGateway/Program.cs index 498282b..47d1d38 100644 --- a/gateways/KonSoft.InternalGateway/Program.cs +++ b/gateways/KonSoft.InternalGateway/Program.cs @@ -1,4 +1,5 @@ using KonSoft.InternalGateway; +using KonSoft.InternalGateway.Extensions; using KonSoft.Shared.Hosting.AspNetCore; using Serilog; @@ -24,6 +25,7 @@ try await app.InitializeApplicationAsync(); app.MapReverseProxy(); app.MapGet("/heath", () => "Online"); + app.UseSwaggerUIWithYarp(); await app.RunAsync(); return 0;