如何修复.net核心应用程序中找不到的swagger.json

问题描述 投票:1回答:2

我正在IIS服务器上部署我的.net核心应用程序,并在未找到swagger.json的swagger UI中面临问题。当我在本地运行它(开发环境)时,一切都运行良好但是当我在IIS服务器上部署它时,它无法找到swagger.json文件。

以前我在.net core 2.1 app中遇到了这个问题,我通过编写下面的代码来解决它,以获得虚拟基本路径。

string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
            basePath = basePath == null ? "/" : (basePath.EndsWith("/") ? basePath : $"{basePath}/");

 app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint($"{basePath}swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = "";
     });

我试过下面的代码来解决它:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
   app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint($"{env.ContentRootPath}swagger/v1/swagger.json", "Test.Web.Api");
       //OR
      c.SwaggerEndpoint($"{env.WebRootPath}swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = "";
     });
 }

但是abouve代码没有工作,因为它返回实际的物理路径而不是虚拟路径。

有没有人知道如何在.net core 2.2中获取虚拟路径,因为Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");无效。任何领导都会有所帮助。

c# asp.net-core asp.net-core-2.2
2个回答
4
投票

我通过在我的.net核心应用程序中添加以下代码来解决我的问题。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
   app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint("./swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = string.Empty;
    });
 }

根据swashbuckle文档,如果您在IIS中托管它,则需要预先添加./。

我希望这个答案可以节省您的时间!


0
投票

您可以通过以下方式修复相同的问题:

包:#region Assembly Swashbuckle.AspNetCore.Swagger,Version = 4.0.1.0

框架:.Net Core 2.2

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
         c.SwaggerEndpoint("/swagger/v1/swagger.json", "Versioned Api v1");
    );
}

当您在本地运行应用程序或在IIS上托管时,这是有效的。

© www.soinside.com 2019 - 2024. All rights reserved.