30

Well, I'm using Swagger for my API documentation and it works perfectly in localhost, the problem begins when I host it on the IIS. For somereason it just doesn't work anymore

localhost:

https://localhost:44381/swagger/index.html

api:

http://200.155.29.14/SimuladorFrete/Swagger/index.html

All I get when I try to open the Swagger after deploying it in the ISS is a blank page and a 500 internal server error, which doesn't say the exception.

Here is my Configure method (startup.cs)

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

    }
    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    app.UseSwagger();
    app.UseStaticFiles();
    app.UseSwaggerUI(c =>
    {
        if (env.IsDevelopment())
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
        }
        else
        {
            // To deploy on IIS
            c.SwaggerEndpoint("/SimulaFrete/swagger/v1/swagger.json", "Web API V1");
        }

    });
}

and here's my ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddNewtonsoftJson();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1",

      new OpenApiInfo
      {

          Title = "Simulador de frete por Unidade",
          Version = "v1",
          Description = "Métodos da API de simulação de frete",
          Contact = new OpenApiContact
          {
              Name = "Catalde Technology",
              Url = new Uri("https://www.catalde.com"),
              Email = "[email protected]"
          }
      });

        string caminhoAplicacao =
            PlatformServices.Default.Application.ApplicationBasePath;
        string nomeAplicacao =
            PlatformServices.Default.Application.ApplicationName;
        string caminhoXmlDoc =
            Path.Combine(caminhoAplicacao, $"{nomeAplicacao}.xml");

        c.IncludeXmlComments(caminhoXmlDoc);
        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); //This line
    });
}

And there's my Controller code which has only this method:

[HttpPost]
public ContentResult Post([FromBody]dadosFrete xml)
{
    // code logic
}
1

8 Answers 8

63

You need to temporarily add the production clause in your condition before you can see the swagger in the production environment. See the yellow highlighted section in the attached image. env.IsProduction()

image

Sign up to request clarification or add additional context in comments.

8 Comments

You didnt add the image correctly, use ![description](link) instead
It works to me if (env.IsDevelopment() || env.IsProduction()), thanks
This answer just made me feel like a flipping idiot well spoted why on earth does boiler plate code add it here.
it works for me in Net6 minimal API if (app.Environment.IsDevelopment() || app.Environment.IsProduction()) { app.UseSwagger(); app.UseSwaggerUI(); }
I would put the UseSwagger and UseSwaggerUI outside of the condition and not put things in the condition that is related to development. Since the us of swagger is necessary for both environment there's no reason to add both statement in the if
|
13

Try this. To set relative path.

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

if this solution not work. Then check publish setting. The issue is that running dotnet publish with -r Release does not produce XML file. However, dotnet publish with -r Debug does in fact produce the file. This explains why people are only getting this issue when they are deploying to environments OTHER than locally. You can simplify find out in Project > Your Project properties > Build Tab

1 Comment

While this might answer the question, you should edit your answer to include an explanation of how this code block answers the question. This makes your answer much more useful to those who come across the same issue later on.
4

The following worked for me. I was able to get it working locally on IIS.

  1. You'll need to publish the project to a folder and point IIS to that folder.
  2. Edit the Configure method and move out Swagger out of env.IsDevelopment and use vipul's solution above to fix the path.
 if (env.IsDevelopment())
 {
   app.UseDeveloperExceptionPage();
 }
 app.UseSwagger();
 app.UseSwaggerUI(c =>
 {
   string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
   c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "Web API");

 });

Comments

1

Take a look at how to use multiple environments in .net core. Some options are

  • using a launch.json file for your different environments (dev/stage/prod) (local dev only)
  • Adding an environment variable named ASPNETCORE_ENVIRONMENT with development, stage or production
  • Or making a web.config to deploy to IIS and add the value
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

For IIS, it all depends on the version of IIS. Older versions of IIS, I believe you can only go with web.config.

Comments

1

I know this is old, but it is top ranking in Google for this issue. None of the above worked for me.I wasn't getting a 500 (or a 404), just a blank Swagger page. I could also open swagger.json OK My real problem was that the Sys Admins don't allow anything other than IE on a server here, so I was testing my deployment (before they had opened the firewall ports) locally using IE. Swagger page opens, but displays nothing in IE. Bending the rules, I installed Edge and swagger was working fine. Hope this saves someone else a wasted morning.

Comments

1

I spent several days troubleshooting. it turned out if I publish in x86 the page displays just fine.

Comments

1

Super old I know but I would not do the accepted answer. You essentially are saying development and production are the same in your code. Bad, BAD, REALLY BAD IDEA to hard code your system as two things. Really you should go into IIS and set the environment variables to have 'ASPNETCORE_ENVIRONMENT' be correct on your IIS site to what you want. Doing it hard coded is not a good idea and leaving on Swagger in production is not advised for many reasons.

  1. So go into IIS.
  2. Go to your site by clicking on it.
  3. Click 'Configuration Editor' under the 'Management' Section on the main viewing pane
  4. Ensure at the top the section is 'system.webServer/aspNETCore'
  5. Ensure the 'From' shows 'ApplicationHost.config' and NOT your web config. (else you will just rewrite it every deploy)
  6. Find environmentVariables about 3 down and click the on value section and the '...'
  7. (Top right of new pane) click 'Add' under 'Collection'
  8. name = ASPNETCORE_ENVIRONMENT value = Development (or whatever environment you want)
  9. (close the screen) Click 'Apply' under 'Actions' at the top right.

I usually refresh the site at this point to make sure it takes and if you did it right, voila now Swagger works. I did this just now in .NET 8 so it works with current versions too.

Comments

1

to host on IIS, I added ".." to relative path and also "|| env.IsProduction() " in conditional statement. Wow it worked for me Under "Setup.cs" file, modified "Configure" method in .Net 6.0 API project

2 Comments

Some strange reason, why publishing to IIS adds another /swagger to the URL...
When publishing a .NET Core API with Swagger/OpenAPI to IIS, the /swagger path is added to the URL because that's the default path configured by the Swagger middleware for serving the Swagger UI and JSON endpoint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.