Publishing web api with swagger on IIS

Viewed 14492

I am trying figure out how to publish a .net core 3 API with Swagger (SwashBuckle) after following this example documentation . So it works locally and when I hit F5 IIS Express launches the site under http://localhost:8033/index.html

Here is the Configure code in startup.cs:

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(env.ContentRootPath),
                RequestPath = new PathString("")
            });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
                c.DocumentTitle = "TestAPI";
                c.DocExpansion(DocExpansion.None);
                c.RoutePrefix = string.Empty;                   
            });                
        }

Next I published the API to a local folder and copied the files to the IIS folder on the server. If I open the server API domain I get a page can’t be found. Which address should I use to open up the swagger UI on the server? Is something missing from the configuration?

3 Answers

There is no problem with your Swagger settings. Please don’t forget configure the Swagger generator, as well as the comments path for the Swagger JSON.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "ToDo API",
                    Description = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "Shayne Boyer",
                        Email = string.Empty,
                        Url = new Uri("https://twitter.com/spboyer"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://example.com/license"),
                    }
                });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }

Besides, Please ensure that the server has installed the Asp.net core hosting bundle on the sever-side.
https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.6-windows-hosting-bundle-installer
Feel free to let me know if there is anything I can help with.

Just to add, it could also be possible that the following nodes are missing from the API project file under the PropertyGroup node.

<RuntimeIdentifiers>win10-x64;</RuntimeIdentifiers>
<AspNetCoreModuleName>AspNetCoreModuleV2</AspNetCoreModuleName>

Edit your Startup.cs File

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

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

        if (env.IsProduction() || env.IsStaging())
        {
            app.UseExceptionHandler("/Error/index.html");
        }

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

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.RoutePrefix = "swagger";
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");

            // custom CSS
            c.InjectStylesheet("/swagger-ui/custom.css");
        });

        app.Use(async (ctx, next) =>
        {
            await next();
            if (ctx.Response.StatusCode == 204)
            {
                ctx.Response.ContentLength = 0;
            }
        });


        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();
        app.UseAuthentication();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseCors();

    }   
    
  

  

https://youtu.be/6HiaXCAlRr0

Related