How to fix swagger.json not found in .net core 2.2 app
Asked Answered
M

7

14

I'm deploying my .net core app on IIS server and facing the issue in swagger UI where swagger.json not found. When I run it locally (Development environment) everything is working perfectly but when I deploy it on IIS server it fails to find swagger.json file.

Previously I was facing this issue in .net core 2.1 app and I resolved it by writing below code to get the virtual base path.

string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
            basePath = basePath == null ? "/" : (basePath.EndsWith("/") ? basePath : $"{basePath}/");

 app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint($"{basePath}swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = "";
     });

I have tried below code to resolve it:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
   app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint($"{env.ContentRootPath}swagger/v1/swagger.json", "Test.Web.Api");
       //OR
      c.SwaggerEndpoint($"{env.WebRootPath}swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = "";
     });
 }

But abouve code didn't worked as it returns actual physical path and not virtual path.

Does anyone know how to get the virtual path in .net core 2.2 as Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH"); is not working. Any lead would be helpful.

Mylohyoid answered 28/1, 2019 at 17:14 Comment(3)
According to the Swashbuckle docs, you should be able to just use "./swagger/v1/swagger.json" and not prepend the hosting URL. Did that not work? Edited to add period to front of path because I noticed this was not running at the root of the domain.Essence
Yes, I have tried that too but didn't work. Failed to fetch the swagger.json file.Mylohyoid
I had similar issue but the reason may be different. if anyone want can view my experience hereNahshun
M
15

I have fixed my issue by putting below code in my .net core app.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
   app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint("./swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = string.Empty;
    });
 }

As per swashbuckle documentation you need to prepend the ./ if you are hosting it in IIS.

I hope this answer will save your time!

Mylohyoid answered 28/1, 2019 at 18:7 Comment(4)
Yup, but I missed "." before "/". Thanks!Mylohyoid
unfortunately this does not work. I have application hosted using IIS express and had set launchsettings.json as "iisExpress": { "applicationUrl": "http://localhost/char", to test IIS virtual directory. However the problem is that localhost/char/swagger shows 404 error but localhost/char/swagger/v1/swagger.json works (the json file is shown). localhost/swagger works fine if there is no path in the applicationUrl value. I'm using netcore31 and Swashbuckle.AspNetCore 5.0.0 packageDraggletailed
@VAAA yes I did. Please check my answer in this threadDraggletailed
This solution saved my life!Kirsti
D
6

I've tried to use c.SwaggerEndpoint("./swagger/v1/swagger.json", "Test.Web.Api"); from the Mahesh's answer but the problem is that it does not help.

I've got Swashbuckle sample started from VS using IIS Express

I'm getting error

Failed to load API definition. undefined ./swagger/v1/swagger.json

when was accessing the localhost/char/swagger endpoint from the web browser.

I had modified launchsettings.json\iisExpress\applicationUrl and added the path like "iisExpress": { "applicationUrl": "http://localhost/char" and Startup.cs source code like

   app.UseSwaggerUI(c =>
     {
      c.SwaggerEndpoint("./swagger/v1/swagger.json", "Test.Web.Api");
      c.RoutePrefix = string.Empty;
    });

The solution was found at the Github issue please find it below:

app.UseSwaggerUI(c =>
{
    string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
    c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "My API");
});

I have not seen it in the documentation but it is working when

  • hosted by IIS Express locally with (or without) additional path after host name in the iisExpress\applicationUrl
  • hosted by IIS on staging environment (with additional path after hostname like http://staginghost/char/swagger
Draggletailed answered 11/2, 2020 at 13:49 Comment(1)
@GabrielSimas this solution is two years old. Try to post new Swashbuckle.WebApi issue it you beleive that did it properly.Draggletailed
H
6

For .net core 5, swagger is added automatically on project creating.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProject.Api", Version = "v1" });
    });
}

However, you need to make sure that two commented lines are out of the if block.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider svp)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseSwagger();
                //app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject.Api v1"));
            }

            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject.Api v1"));                 

        }
Herwin answered 22/12, 2020 at 9:45 Comment(0)
K
4

i have faced this issue and found that you have to match the exact typing of Version in the path and both servicescollection and appbuilder

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

 app.UseSwagger(); app.UseSwaggerUI(c => { 
    c.SwaggerEndpoint("/swagger/v1/swagger.json","MyApp API v1"); });
Kellam answered 28/1, 2021 at 4:31 Comment(0)
H
2

In my cases I forgot to add HTTPGet Attribute one of my controller public get method

Hyponasty answered 17/1, 2021 at 13:5 Comment(0)
M
0

You can fix the same in the following way:

Package: #region Assembly Swashbuckle.AspNetCore.Swagger, Version=4.0.1.0

Framework: .Net Core 2.2

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
         c.SwaggerEndpoint("/swagger/v1/swagger.json", "Versioned Api v1");
    );
}

This is work when you run the application locally or hosted on IIS.

Marlanamarlane answered 12/3, 2019 at 8:52 Comment(0)
E
0

For .Net Core 2.2

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

then

 // 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();
            app.UseOpenApi();
            app.UseSwaggerUi3();

        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
Erleneerlewine answered 22/5, 2020 at 18:10 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Havre

© 2022 - 2024 — McMap. All rights reserved.