【问题标题】:Swagger failing with Failed to load API definition (yet another thread)Swagger 失败并无法加载 API 定义(又一个线程)
【发布时间】:2019-06-12 11:06:42
【问题描述】:

我尝试将 swagger 添加到现有的 api,在失败了很多之后,我决定创建一个新的解决方案,创建一个新的 asp.net core 2.2 api 并按照

https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=visual-studio

关于此问题的其他帖子似乎都表明存在多个 httpverb 或没有的情况,默认值控制器并非如此。它给了我错误

未能加载 API 定义。

获取错误,服务不可用 /swagger/v1/swagger.json

api/swagger/v1/swagger.json 中的实际 json 文件实际上可以正确渲染

我的创业班是

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddSwaggerGen(c =>{
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

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

我使用的是 Swachbuckle.AspNetCore v 4.01。

【问题讨论】:

  • 根据我的经验,这通常发生在您的控制器设置不正确时。您能否发布您的控制器进行审核,我们可以检查问题可能是什么。

标签: asp.net-core-webapi swagger-ui swagger-2.0 asp.net-core-2.2


【解决方案1】:
        String SwaggerEndpoint = "/swagger/v1/swagger.json";

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
            SwaggerEndpoint = "/andi/swagger/v1/swagger.json";
        }


        app.UseMvc();

        app.UseSwagger();
        app.UseSwaggerUI(options =>
        {
            options.SwaggerEndpoint(SwaggerEndpoint, "My API");
            //options.RoutePrefix = string.Empty;
        });

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2019-12-23
    • 2021-06-03
    • 2018-09-18
    • 2020-10-29
    • 2019-11-13
    • 1970-01-01
    • 2020-06-06
    • 2022-06-21
    相关资源
    最近更新 更多