简体   繁体   English

Swagger 不生成 swagger.json

[英]Swagger is not generating swagger.json

I have the asp.net core MVC project and separate WebApi project in one solution.我在一个解决方案中有 asp.net 核心 MVC 项目和单独的 WebApi 项目。 I'm adding the swagger following the documentation on github. Here is my Startup.cs of mvc project:我正在按照 github 上的文档添加 swagger。这是我的 mvc 项目的 Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        //...
        // Adding controllers from WebApi:
        var controllerAssembly = Assembly.Load(new AssemblyName("WebApi"));
        services.AddMvc(o =>
            {
                o.Filters.Add<GlobalExceptionFilter>();
                o.Filters.Add<GlobalLoggingFilter>();
            })
            .AddApplicationPart(controllerAssembly)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

        services.AddSwaggerGen(c =>
        {
            //The generated Swagger JSON file will have these properties.
            c.SwaggerDoc("v1", new Info
            {
                Title = "Swagger XML Api Demo",
                Version = "v1",
            });
        });

        //...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //...
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML Api Demo v1");
        });

        //...

        app.UseMvc(routes =>
        {
            // ...
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Here are the nugets:这是核心:

小块

The WebApi controllers Attribute routing: WebApi 控制器属性路由:

[Route("api/[controller]")]
public class CategoriesController : Controller
{
    // ...
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        return Ok(await _repo.GetCategoriesEagerAsync());
    }
    // ...
}

When I'm trying to go to /swagger it doesn't find the /swagger/v1/swagger.json:当我尝试将 go 转到 /swagger 时,它找不到 /swagger/v1/swagger.json: 未找到 Json

What I'm doing wrong?我做错了什么?

Thanks in advance!提前致谢!

I was stuck on this problem for hours... and I found the reason...我被这个问题困了几个小时......我找到了原因......

Check the code below !!检查下面的代码!

.. Startup.cs .. ..启动.cs ..

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

    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseSwagger(); // if I remove this line, do not work !
    app.UseSwaggerUi3();
}

Just wanted to add my experience here as well.只是想在这里添加我的经验。 I have given the version in configureServices as V1 (notice the V in caps) and我已将configureServices中的版本指定为V1 (注意大写的V )和

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", //this v was in caps earlier
            new Swashbuckle.AspNetCore.Swagger.Info
            {
                Version = "v1",//this v was in caps earlier
                Title = "Tiny Blog API",
                Description = "A simple and easy blog which anyone love to blog."
            });
        });
        //Other statements
    }

And then in the configure method it was in small case然后在configure方法中它是小情况

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

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

May be it can help someone.也许它可以帮助某人。

Check if you set environment correctly, and is the command app.UseSwagger isn't inside a if to execute only on a determined environment like development.检查您是否正确设置了环境,并且命令app.UseSwagger不在 if 中,仅在确定的环境(如开发)上执行。

A test solution is to add the line app.UseSwagger( ) outside any conditional statement.一个测试解决方案是在任何条件语句之外添加行app.UseSwagger( )。

Here's some sample code using .net core 6:下面是一些使用 .net 核心 6 的示例代码:

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(s =>
{
    s.SwaggerDoc("v1", new OpenApiInfo { Title = "Service Manager API", Description = "API Docs for the Service Manager Layer.", Version = "v1"});
});

var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Service Manager API V1");
});

app.Run();

I ran into the problem simply by not adding "/" to the Path (/swagger/v1... not swagger/v1/...我只是因为没有在路径中添加“/”而遇到了这个问题(/swagger/v1...不是 swagger/v1/...

暂无
暂无

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

相关问题 Generating C# Rest API Client from swagger.json - Generating C# Rest API Client from swagger.json 显示 Swagger.json 但 UI 不显示 - Swagger.json is displayed but the UI not .net core/swagger - 生成 swagger.json 文件时如何绕过控制器文件? - .net core/swagger - How can I around a controller file when generating the swagger.json file? 使用 GenerateSchema 添加的类出现在 Swagger UI 中,但不在 swagger.json 中 - Classes Added Using GenerateSchema Appear in the Swagger UI But Not in swagger.json 从基础 controller 继承 controller 操作时生成 swagger.json 文件的问题 - Issue generating swagger.json file when inheriting controller actions from a base controller Swagger 'swagger.json' 加载,但在 AspNet 项目中的 swagger UI '{localhost}/swagger' 上出现 404 错误 - Swagger 'swagger.json' loads, but 404 error on swagger UI '{localhost}/swagger' in AspNet project 当本地主机提供 swagger.json 时,Autorest 无法针对文件解析 swagger.json - Autorest Failed resolving swagger.json against file when swagger.json is served by localhost Blazor Swagger:无法加载 API 定义。 获取错误:未定义 /swagger/v1/swagger.json - Blazor Swagger: Failed to load API definition. Fetch error: undefined /swagger/v1/swagger.json 如何修复 .net core 2.2 应用程序中未找到的 swagger.json - How to fix swagger.json not found in .net core 2.2 app swagger.json 路径和定义为空。 规范中没有定义操作 - swagger.json paths and definitions are empty. No operations defined in spec
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM