Nikita Fedorov
Nikita Fedorov

Reputation: 870

Swagger is not generating swagger.json

I have the asp.net core MVC project and separate WebApi project in one solution. I'm adding the swagger following the documentation on github. Here is my Startup.cs of mvc project:

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:

nugets

The WebApi controllers Attribute routing:

[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: Json not found

What I'm doing wrong?

Thanks in advance!

Upvotes: 5

Views: 17806

Answers (6)

Platedslicer
Platedslicer

Reputation: 77

If you are mapping any minimal API methods along with your controller methods, this might be worth a look...

Recently, after a VS2022 update (and presumably an update to .NET 6 binaries), the delegate passed to the SwaggerGenOptions.TagActionsBy method in our custom AddSwaggerGen began to be called for a minimal API action that had until then been ignored:

app.MapGet("/minimal/sabotage", () => "I'll break you");

Because of how our TagActionsBy delegate worked (which I suspect was generated by a .NET Framework Web API template at some point before it was migrated to .NET 6), the lack of a GroupName or a ControllerActionDescriptor in the ApiDescription parameter caused an InvalidOperationException to be thrown, and the swagger.json generation to fail.

This was very easy to fix; just had to add a group name to the method registration:

app.MapGet("/minimal/sabotage", () => "I'll break you").WithGroupName("minimal");

Upvotes: 0

Shashank
Shashank

Reputation: 101

Here is one more reason, if you are missing adding [HttpGet(Name = "")] attributed on top of your action method.

If this help to anyone.

Upvotes: 0

Michael Staples
Michael Staples

Reputation: 577

Here's some sample code using .net core 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/...

Upvotes: 1

Rodolfo Bortoluzzi
Rodolfo Bortoluzzi

Reputation: 1

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.

A test solution is to add the line app.UseSwagger() outside any conditional statement.

Upvotes: 0

Iftikhar Ali Ansari
Iftikhar Ali Ansari

Reputation: 1760

Just wanted to add my experience here as well. I have given the version in configureServices as V1 (notice the V in caps) and

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

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.

Upvotes: 2

Diego S. Chagas
Diego S. Chagas

Reputation: 31

I was stuck on this problem for hours... and I found the reason...

Check the code below !!

..Startup.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();
}

Upvotes: 3

Related Questions