简体   繁体   English

如何修复 .net core 2.2 应用程序中未找到的 swagger.json

[英]How to fix swagger.json not found in .net core 2.2 app

I'm deploying my .net core app on IIS server and facing the issue in swagger UI where swagger.json not found.我正在 IIS 服务器上部署我的 .net 核心应用程序,并面临 swagger UI 中找不到 swagger.json 的问题。 When I run it locally (Development environment) everything is working perfectly but when I deploy it on IIS server it fails to find swagger.json file.当我在本地(开发环境)运行它时,一切正常,但是当我将它部署在 IIS 服务器上时,它找不到 swagger.json 文件。

Previously I was facing this issue in .net core 2.1 app and I resolved it by writing below code to get the virtual base path.以前我在 .net core 2.1 应用程序中遇到过这个问题,我通过编写下面的代码来获取虚拟基本路径来解决它。

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 = "";
     });

I have tried below code to resolve it:我试过下面的代码来解决它:

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 = "";
     });
 }

But abouve code didn't worked as it returns actual physical path and not virtual path.但是上面的代码不起作用,因为它返回实际的物理路径而不是虚拟路径。

Does anyone know how to get the virtual path in .net core 2.2 as Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");有谁知道如何在 .net core 2.2 中获取虚拟路径作为Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH"); is not working.不管用。 Any lead would be helpful.任何线索都会有所帮助。

I have fixed my issue by putting below code in my .net core app.我通过在我的 .net 核心应用程序中放置以下代码来解决我的问题。

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

As per swashbuckle documentation you need to prepend the ./ if you are hosting it in IIS.根据swashbuckle文档,如果您在 IIS 中托管它,则需要预先添加 ./ 。

I hope this answer will save your time!我希望这个答案可以节省您的时间!

I've tried to use c.SwaggerEndpoint("./swagger/v1/swagger.json", "Test.Web.Api");我试过使用c.SwaggerEndpoint("./swagger/v1/swagger.json", "Test.Web.Api"); from the Mahesh's answer but the problem is that it does help.来自Mahesh 的回答,但问题是它确实有帮助。

I've got Swashbuckle sample started from VS using IIS Express我已经使用 IIS Express 从 VS 启动了Swashbuckle 示例

I'm getting error我收到错误

Failed to load API definition.未能加载 API 定义。 undefined ./swagger/v1/swagger.json未定义 ./swagger/v1/swagger.json

when was accessing the localhost/char/swagger endpoint from the web browser.何时从 Web 浏览器访问localhost/char/swagger端点。

I had modified launchsettings.json\\iisExpress\\applicationUrl and added the path like "iisExpress": { "applicationUrl": "http://localhost/char" and Startup.cs source code like我修改了launchsettings.json\\iisExpress\\applicationUrl并添加了类似"iisExpress": { "applicationUrl": "http://localhost/char"Startup.cs源代码这样的路径

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

The solution was found at the Github issue please find it below:解决方案是在Github 问题中找到的,请在下面找到它:

app.UseSwaggerUI(c =>
{
    string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
    c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "My API");
});

I have not seen it in the documentation but it is working when我没有在文档中看到它,但它在工作时

  • hosted by IIS Express locally with (or without) additional path after host name in the iisExpress\\applicationUrl由 IIS Express 在本地托管,在iisExpress\\applicationUrl中的主机名之后带有(或不带有)附加路径
  • hosted by IIS on staging environment (with additional path after hostname like http://staginghost/char/swagger由 IIS 在登台环境中托管(在主机名后有额外的路径,如http://staginghost/char/swagger

For .net core 5, swagger is added automatically on project creating.对于 .net core 5,在项目创建时会自动添加 swagger。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProject.Api", Version = "v1" });
    });
}

However, you need to make sure that two commented lines are out of the if block.但是,您需要确保两条注释行在 if 块之外。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider svp)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseSwagger();
                //app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject.Api v1"));
            }

            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject.Api v1"));                 

        }

i have faced this issue and found that you have to match the exact typing of Version in the path and both servicescollection and appbuilder我遇到过这个问题,发现您必须匹配路径中版本的确切类型以及 servicescollection 和 appbuilder

 services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1" , new OpenApiInfo{ Title = "MyApp API" , Version = "v1" });
 });

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

在我的情况下,我忘记添加 HTTPGet 属性我的控制器公共获取方法之一

You can fix the same in the following way:您可以通过以下方式修复相同的问题:

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

Framework: .Net Core 2.2框架:.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");
    );
}

This is work when you run the application locally or hosted on IIS.当您在本地运行应用程序或托管在 IIS 上时,这是可行的。

For .Net Core 2.2对于 .Net Core 2.2

  // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerDocument();

then然后

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseOpenApi();
            app.UseSwaggerUi3();

        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM