[SOLVED] Can't read swagger JSON file on ASP.NET Core 1.2 Application after hosting into local IIS

Issue

After hosting my asp.net core 1.2 application, I am getting an error as:

swagger is unable to find the swagger.json file.

I have tried to solve the problem by giving a virtual path name app.UseSwaggerUI() but it’s not working.

Edit to clarify question based on comments:

After hosting Asp.net core application in IIS, the swagger.json file is generating on localhost:<random_port>/swagger/v1/swagger.json path.

How do I serve the swagger.json file on a custom route like:
localhost:<random_port>/virtualpathname/swagger/v1/swagger.json

I have tried to set a virtual path in app.UseSwaggerUI() like {virtualpathname}/swagger/v2/swagger.json but still it is not working

Solution

Could be a few reasons for this – one being that .Net Core doesnt serve static files by default (although looking at online examples this doesnt seem to be an issue).

If you havent already, try installing the package Microsoft.AspNetCore.StaticFiles and adding UseStaticFiles() in your Configure() method in Startup.cs with the following configuration. I dont think that the order is important, but this is the order I have mine running in a working app.

public void Configure(...)
{
  // Enable middleware to serve static files (like .json)
  app.UseStaticFiles();

  //Enable middleware for your API
  app.UseMvc();

  // Enable middleware to serve generated Swagger as a JSON endpoint
  app.UseSwagger();

  // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
  app.UseSwaggerUI(c =>
  {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "YourApp API V1");
  });
}

You will also need SwaggerGen middleware configured in your ConfigureServices() method.

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

Edit Based on comment – to serve swagger json on a custom route:

// Enable middleware to serve generated Swagger as a JSON endpoint on a custom endpoint
app.UseSwagger(c => c.RouteTemplate = "custom/swagger/{documentName}/swagger.json");

// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
// Using custom endpoint defined above
app.UseSwaggerUI(c =>
{
  c.SwaggerEndpoint("/custom/swagger/v1/swagger.json", "YourApp API V1");
});

If you need to serve SwaggerUI on a custom route as well, then:

// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
// Using custom endpoint defined above
// And serving UI on a custom route
app.UseSwaggerUI(c =>
{
  c.SwaggerEndpoint("/custom/swagger/v1/swagger.json", "YourApp API V1");
  c.RoutePrefix = "custom"; // serves UI on http://{domain}:{port}/custom/
});

Answered By – Steve Land

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *