首页 > 解决方案 > 为什么 SwaggerForOcelot 不加载服务 swagger 端点 .NET 6?

问题描述

我正在测试 .NET 6 rc.1 并尝试设置一个具有微服务结构的项目。现在我有2个项目:

  1. 身份验证API
  2. API网关

我在 Authentication API 项目中创建了一些端点并设置了 APIGateway ocelot.json 文件(在我的例子中,我创建了一个文件 ocelot.authentication.json)。

我尝试了一些解决方案,但似乎没有任何效果。我的第一个解决方案是在 ocelot.authentication.json 中添加 SwaggerEndPoints 键,但这不起作用,因为生成 ocelot.json 时不要读取主 ocelot.json 文件中的键。我尝试将 SwaggerEndPoints 键放在 application.json 中,但这不起作用。现在我尝试在 Program.cs 上手动添加端点并且这项工作,但服务 swagger 配置路径可能存在一些问题,因为我需要设置一个替代路径,如 /auth/swagger 而不是 /swagger。如果我尝试配置完整路径(http://localhost:5200/swagger),则会出现 cors 问题。

那么,如何为自定义端点配置服务招摇或在文件中配置 SwaggerEndPoints?

在 AuthenticationAPI 上招摇

app.UseSwagger();
app.UseSwaggerUI(setup =>
{
    setup.SwaggerEndpoint("/swagger/v1/swagger.json", "Authentication API v1");
   
});

使用最小 API 在 APIGateway 上大摇大摆

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddOcelot(builder.Environment);
builder.Services.AddOcelot(builder.Configuration);
builder.Services.AddSwaggerForOcelot(builder.Configuration);
builder.Services.AddMvc();

WebApplication app = builder.Build();

app.UseSwaggerForOcelotUI(options =>
{
    options.DownstreamSwaggerEndPointBasePath = "/swagger";
    options.PathToSwaggerGenerator = "/swagger/docs";
    options.SwaggerEndpoint("https://localhost:5201/swagger", 
    "Authentication API");
}).UseOcelot().Wait();

app.Run();

在这种情况下,我有 CORS 错误: CORS 错误

感谢您的任何建议!

更新

所有 ocelot.*.json 文件现在都在 Configuration 文件夹中。我添加了带有 swagger 配置的 ocelot.SwaggerEndPoints.json 并更新了初始化:

程序.cs

using MMLib.SwaggerForOcelot.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddOcelotWithSwaggerSupport(options =>
{
    options.Folder = "Configuration";
});
builder.Services.AddOcelot(builder.Configuration);
builder.Services.AddSwaggerForOcelot(builder.Configuration);
builder.Services.AddMvc();

WebApplication app = builder.Build();

app.UseSwaggerForOcelotUI(options =>
{
    options.PathToSwaggerGenerator = "/swagger/docs";
}).UseOcelot().Wait();

app.Run();

现在它工作正常。

标签: .netswaggermicroservicesswagger-uiocelot

解决方案


推荐阅读