簡體   English   中英

How to set BaseUrl for Swagger in ASP.NET Core Web API using NSwag.AspNetCore (when hosted behind a reverse proxy)

[英]How to set BaseUrl for Swagger in ASP.NET Core Web API using NSwag.AspNetCore (when hosted behind a reverse proxy)

我正在努力應對以下情況:

我有一個 ASP.NET 內核 Web API 在 Startup.

    public void ConfigureServices(IServiceCollection services)
    {
      ...

      services.AddSwaggerDocument(config =>
      {
        config.PostProcess = document =>
        {
          document.Info.Version = "v1";
          document.Info.Title = "...";
        };
      });

      ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      ...

      app.UseOpenApi();
      app.UseSwaggerUi3();

      ...
    }

如果我在本地運行 api 一切正常。 Means I can access the Swagger page at http://localhost:5000/swagger/index.html and execute requests from there against the api which is available at http://localhost:5000/api .

在生產中,我的 api 在 Docker 容器內運行,並在反向代理后面。 The container exposes the Swagger page at http://localhost:5000/swagger/index.html and the reverse proxy maps external requests to https://my.domain.com to http://localhost:5000 internally. 這樣我實際上可以訪問http://my.domain.com/swagger/index.html的 Swagger 頁面。 到目前為止一切都很好。

問題是當我想從該生產 Swagger 頁面對我的 api 執行請求時。 我在瀏覽器開發工具的網絡選項卡中看到 Swagger 仍然將請求發送到http://localhost:5000/api什么當然不起作用。 相反,它應該將請求發送到https://my.domain.com/api 同樣在標題下方,Swagger 頁面狀態為[ Base URL: localhost:5000 ]

I am not able to figure out how I could configure Swagger to use whatever base url I provide (like https://my.domain.com/ in my current case) so that I could execute requests against the api from anywhere and also that標題下方的 BaseUrl 是正確的。

有人可以在這里幫助我嗎?

同時我自己想通了。 解決方案是刪除 localhost 服務器(由 ASP.NET 核心中間件添加)並添加我自己的一個,如下所示:

app.UseOpenApi(settings =>
{
  settings.PostProcess = (document, httpRequest) =>
  {
    document.Servers.Clear();
    document.Servers.Add(new OpenApiServer { Url = "..." });
  };
});

此問題/評論將我引向正確的方向: https://github.com/RicoSuter/NSwag/issues/2441#issuecomment-583721522

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM