SwaggerEndPoints 配置访问外部 Swagger 文档
在 appsettings.json
中添加 Swagger 端点配置
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"SwaggerEndPoints": [{"Key": "plant","Config": [{"Name": "CentData API","Version": "v1","Url": "http://127.16.34.22:55002/swagger/v1/swagger.json" // 模拟的外部 Swagger URL}]},{"Key": "Alarm","Config": [{"Name": "AlarmData API","Version": "v1","Url": "http://127.16.34.22:55004/swagger/v1/swagger.json" // 模拟的外部 Swagger URL}]}],"AllowedHosts": "*"
}
修改 Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System.Collections.Generic;public class Startup
{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }public void ConfigureServices(IServiceCollection services){services.AddControllers();services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Documentation", Version = "v1" });// 从配置中读取 Swagger 端点var swaggerEndpoints = Configuration.GetSection("SwaggerEndPoints").Get<List<SwaggerEndpointConfig>>();foreach (var endpoint in swaggerEndpoints){foreach (var config in endpoint.Config){c.SwaggerDoc(endpoint.Key, new OpenApiInfo { Title = config.Name, Version = config.Version });}}});}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseRouting();app.UseAuthorization();// 启用 Swagger 中间件app.UseSwagger();app.UseSwaggerUI(c =>{c.RoutePrefix = "swagger"; // Swagger UI 的前缀var swaggerEndpoints = Configuration.GetSection("SwaggerEndPoints").Get<List<SwaggerEndpointConfig>>();foreach (var endpoint in swaggerEndpoints){foreach (var config in endpoint.Config){// 使用 Url 属性来添加外部 Swagger 端点if (!string.IsNullOrWhiteSpace(config.Url)){c.SwaggerEndpoint(config.Url, $"{config.Name} v{config.Version}");}else{c.SwaggerEndpoint($"/swagger/{endpoint.Key}/swagger.json", $"{config.Name} v{config.Version}");}}}});app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
}// Swagger 端点配置类
public class SwaggerEndpointConfig
{public string Key { get; set; }public List<SwaggerConfig> Config { get; set; }
}public class SwaggerConfig
{public string Name { get; set; }public string Version { get; set; }public string Url { get; set; } // Optional: 如果您希望直接使用 URL
}