7

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?

2

5 Answers 5

6

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.

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

2 Comments

Hi @AbrahamQian thanks for your explanation. I have all the code in place and the API is working that is I am able to trigger a REST call from a client. However the SwaggerUI isn´t shown on the server. I assume it should be enough to point to the index.html like this MyServerAPI/index.html ? Even though there are no static files or wwwroot folder located in the project I assume the Swagger will generate this on the fly?
yes, the URL is enough to navigate the SwaggerUI. But I am not sure about the second question. You could try to configure in the CSPROJ file to allow the compiler to generate a file , just like the document said.
5

Assuming we're using ASP.NET Core / 7 for building the web api. For .NET 7 (or minimal api) we need to try commenting / adjusting the snippet below in Program.cs

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    app.UseSwaggerUI();
//}

Next build / publish using VS / VS Code And access your API on local dev / test: https://local-api.{yur-api-name}.com/{service-name}Services/swagger/index.html

2 Comments

This resolved it for me. Thanks! I had specific code around those two lines, only for when in Development environment. Removed the restriction and works like a charm
Thanks a million. my problem has been resolved by this answer. I didn't know how to publish my swagger UI.
1

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

Comments

0

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>

Comments

0

For people looking for ASP.NET Core version 6/7/8 and want to turn on easily through the web.config file on save a remote deployment. This assumes you have left the default in your program.cs or default configuration code start up.

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

DISCLAIMER: Only enable this on a protected server or behind a private VPN or firewall Development/Sandbox/Staging servers. Never use in a PRODUCTION environment. To enable easily on your local/remote deployment and see Swagger interface for testing.

  1. STOP IIS Service
  2. Edit your root directory Web.config -> Add the environment variable section and set the variable below.
  3. Then START IIS Service
  4. Visit your https://{web address}{port}/swagger/index.html

Example WEB.CONFIG

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\{yourprojectname}.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" >
    <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
    </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
</configuration>

Comments

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.