using Microsoft.AspNetCore.Builder; 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.SwaggerEndpoint(new Uri(new Uri(clusterGroup.Value.Address), "/swagger/v1/swagger.json").AbsoluteUri, $"{routeConfig.RouteId} API"); options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]); options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]); } }); return app; } } }