51 lines
2.3 KiB
C#
51 lines
2.3 KiB
C#
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<IConfiguration>();
|
|
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
|
|
var proxyConfigProvider = serviceProvider.GetRequiredService<IProxyConfigProvider>();
|
|
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();
|
|
var gatewayUrl = configuration["GatewayUrl"];
|
|
|
|
options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
|
|
options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
|
|
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(!string.IsNullOrWhiteSpace(gatewayUrl)? gatewayUrl: clusterGroup.Value.Address), $"{routeConfig.RouteId.Split("-")[0]}/swagger/v1/swagger.json").AbsoluteUri, $"{routeConfig.RouteId} API");
|
|
}
|
|
});
|
|
|
|
return app;
|
|
}
|
|
}
|
|
}
|