ASP.NET Core Web API with Swagger

Publish a Web API and keep the Swagger UI available in production.

An ASP.NET Core Web API is published the same way as any other .NET application. The only surprise is Swagger: the project template enables it for the Development environment only, so after publishing the Swagger page is gone unless you change one condition.

Before you start

Create the project

  1. Choose the template

    In Visual Studio create a new project, select ASP.NET Core Web API and click Next.

  2. Finish the wizard

    Fill in the additional information and click Create.

Enable Swagger in production

On the hosting your application runs in the Production environment. If Swagger should be available there, comment out this condition in Program.cs:

if (app.Environment.IsDevelopment())

The result looks like this:

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    // Swagger will be available also on production hosting
    app.UseSwagger();
    app.UseSwaggerUI();
//}

Warning

Swagger describes your whole API to anyone who opens it. Publish it in production only if that is what you want.

Publish

  1. Download the publish profile

    In the Control Panel open your website, choose Deploy, switch WebDeploy to Enabled on the Visual Studio access card and click Download publish profile. Save the .publishSettings file.

  2. Import the profile

    In Solution Explorer right-click the project and choose Publish. Click Import profile and select the .publishSettings file.

  3. Publish

    Click Publish. Visual Studio builds the Web API project and publishes it to your website.

  4. Open Swagger

    Open the website in your browser and go to /swagger/index.html.

The home page returns 404

That is expected. A Web API answers only on its own routes, so the root address of the website has no content. See 404 on the home page of a Web API.

Still stuck? Our support team is happy to help.
Ask the community Open a support ticket