当某些请求路径被替换时,如何设置 Swashbucle 以找到 swagger.json?

How do I setup Swashbucle to find the swagger.json when some of the request path is replaced?

我正在尝试将 .net api 升级到 .net core 3.1。 为此,我还必须升级到 Swashbuckle.AspNetCore 5.0。 这在本地主机中开箱即用,但在部署时找不到 swagger.json 文件。

Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{    
    app.Use(async (context, next) =>
    {
        context.Request.Path = context.Request.Path.Value.Replace("/api-svc", "");
        await next.Invoke();
    });
    app.UseSwagger();

    app.UseSwaggerUI(s =>
    {
        s.SwaggerEndpoint("/swagger/v1/swagger.json", "api v1");
    });
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseDefaultFiles();
    app.UseMiddleware<CustomExceptionHandlerMiddleware>();
    app.UseResponseCompression();
    app.UseCors("AllowAll");
    app.UseRouting();
    app.UseAuthentication();
    app.UseMvc();
}

Fetch error: undefined /swagger/v1/swagger.json

网络显示它正在尝试从此 url 检索文件: https://api.com/swagger/v1/swagger.json 哪个正确给出了错误:

Load balancer has no matching route. There is something wrong with your request!.

url 应该是: https://api.com/api-svc/swagger/v1/swagger.json。因为当我手动输入它时,它会响应 json 文件。

所以我尝试设置基本路径 (https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1173);

if (env.IsDevelopment())
{
    app.UseSwagger();

    app.UseSwaggerUI(s =>
    {
        s.SwaggerEndpoint("/swagger/v1/swagger.json", "api v1");
    });
}
else
{
    app.UseSwagger(c =>
    {
        c.PreSerializeFilters.Add((swaggerDoc, request) =>
        {
            swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{request.Scheme}://{request.Host.Value}{Configuration["VIRTUAL_PATH"]}" } };
        });
    });
    app.UseSwaggerUI(s =>
    {
        s.SwaggerEndpoint("/swagger/v1/swagger.json", "api");
    });
}

但同样的错误仍然存​​在。谁能指出我正确的方向?

[更新]

(https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1253) 使用相对路径使一切看起来正确:

app.UseSwagger();
app.UseSwaggerUI(s => {
    s.SwaggerEndpoint("v1/swagger.json", "api v1");
});

现在的问题是实际的api请求url是https://api.com/health when it should be https://api.com/api-svc/health

好的,经过大量测试我找到了答案:

if (env.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(s =>
    {
        s.SwaggerEndpoint("v1/swagger.json", "api v1");
    });
}
else
{
    app.UseSwagger(c =>
    {
        c.PreSerializeFilters.Add((swaggerDoc, request) =>
        {
            var path = Configuration["VIRTUAL_PATH"];
            swaggerDoc.Servers = new List<OpenApiServer> 
            {
                new OpenApiServer { Url = $"https://{request.Host.Value}{path}" } 
            };
        });
    });
    app.UseSwaggerUI(s =>
    {
        s.SwaggerEndpoint("v1/swagger.json", "api");
    });
}