ASP.NET Core - Swashbuckle not creating swagger.js

2019-02-21 12:29发布

问题:

I am having trouble getting the Swashbuckle.AspNetCore (1.0.0) package to generate any output. I read the swagger.json file should be written to '~/swagger/docs/v1'. However, I am not getting any output.

I started with a brand new ASP.NET Core API project. I should mention this is ASP.NET Core 2. The API works, and I am able to retrieve values from the values controller just fine.

My startup class has the configuration exactly as described in this article (Swashbuckle.AspNetCore on GitHub).

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

    public IConfiguration Configuration { get; }

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

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

    // 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();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
            });
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseStatusCodePages();
        app.UseMvc();

        //throw new Exception();
    }
}

You can see the NuGet references...

Again, this is all the default template, but I include the ValuesController for reference...

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

回答1:

I believe you missed these two lines on your Configure:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
    });
}

To access Swagger UI, the URL should be: http://localhost:XXXX/swagger/

The json can be found at the top of Swagger UI:



回答2:

#if DEBUG
   // For Debug in Kestrel
   c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
#else
   // To deploy on IIS
   c.SwaggerEndpoint("/webapi/swagger/v1/swagger.json", "Web API V1");
#endif

When deployed to IIS webapi(base URL) is the Application Alias. You need to keep Application Alias(base URL) same for all IIS deployments because swagger looks for swagger.json at "/swagger/v1/swagger.json" location but wont prefix application Alias(base URL) that is the reason it wont work.

For Example:

localhost/swagger/v1/swagger.json - Couldn't find swagger.json



回答3:

I was running into a similar, but not exactly the same issue with swagger. Hopefully this helps someone else.

I was using a custom document title and was not changing the folder path in the SwaggerEndPoint to match the document title. If you leave the endpoint pointing to swagger/v1/swagger.json it won't find the json file in the swagger UI.

Example:

services.AddSwaggerGen(swagger =>
        {
            swagger.SwaggerDoc("AppAdministration", new Info { Title = "App Administration API", Version = "v1.0" });

        });


 app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/AppAdministration/swagger.json", "App Administration");
        });


回答4:

I had the same problem. Check http://localhost:XXXX/swagger/v1/swagger.json. If you get any a errors, fix them.

For example, I had an ambiguous route in a base controller class and I got the error: "Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0.". If you use base controllers make sure your public methods use the HttpGet/HttpPost/HttpPut/HttpDelete OR Route attributes to avoid ambiguous routes.

Then, also, I had defined both HttpGet("route") AND Route("route") attributes in the same method, which was the last issue for swagger.



回答5:

Personally I had the same issue and when I tried again today after a while I found in the new version (2.5.0) that going in the json I could see an explanation of the error that was in here.

Also another thing that helped to fix it to me was removing the hosting information connected to the website that is hold inside "..vs\config\applicationhost.config" at the root of the solution folder

I removed the element that was configuring the website.

           <site name="**" id="9">
              <application path="/" applicationPool=""></application>
              <bindings></bindings>
           </site>


回答6:

If your application is hosted on IIS/IIS Express try the following:

c.SwaggerEndpoint("../swagger/v1/swagger.json", "MyAPI V1");


回答7:

You must conform 2 rules:

  1. Decorate all actions with explicit Http Methods like[HttpGet("xxx")],[HttpPost("xxx")] or ... instead of [Route("xxx")].
  2. Decorate public methods in controllers with [NoAction] Attribute.

Note that http://localhost:XXXX/swagger/ page requests for http://localhost:XXXX/swagger/v1/swagger.json file, but an Exception will occur from Swagger if you wouldn't conform above rules.



回答8:

I have came across the same issue, and noticed that my API has not hosted in the root folder and in an virtual directory. I moved my API to the root folder in IIS and worked.

More info in this answer