Swagger UI not displaying when deploying API on IIS
Asked Answered
P

8

29

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
}
Pamella answered 15/6, 2020 at 21:32 Comment(1)
S
58

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

Sontich answered 19/2, 2021 at 11:0 Comment(8)
You didnt add the image correctly, use ![description](link) insteadSelfesteem
It works to me if (env.IsDevelopment() || env.IsProduction()), thanksBurr
This answer just made me feel like a flipping idiot well spoted why on earth does boiler plate code add it here.Gabriella
it works for me in Net6 minimal API if (app.Environment.IsDevelopment() || app.Environment.IsProduction()) { app.UseSwagger(); app.UseSwaggerUI(); }Shurlocke
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 ifAir
after change working for me... if (env.IsDevelopment() || env.IsProduction())Wages
I thought of deploying in debug mode, but that didn't work... Does that mean these are 2 different things to consider ?Samuele
You are my best friend today :) Thank you very much Adeshina. I will pray for you.Aseptic
D
12

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

Dollfuss answered 15/6, 2020 at 23:27 Comment(1)
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.Meagan
G
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");

 });

Garfieldgarfinkel answered 13/8, 2022 at 22:49 Comment(0)
E
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.

Endrin answered 19/2, 2021 at 16:34 Comment(0)
G
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.

Gyre answered 29/3, 2023 at 4:7 Comment(0)
P
1

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

Permeance answered 6/12, 2023 at 17:36 Comment(0)
C
0

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.

Convincing answered 6/6 at 1:46 Comment(0)
U
-2

Simply edit your csproj file and add the following snippet

<PropertyGroup>
 <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
Unwinking answered 17/6, 2022 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.