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
- A website created in the Control Panel — see Create your first website.
- Visual Studio with the ASP.NET and web development workload.
Create the project
Choose the template
In Visual Studio create a new project, select ASP.NET Core Web API and click Next.
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
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
.publishSettingsfile.Import the profile
In Solution Explorer right-click the project and choose Publish. Click Import profile and select the
.publishSettingsfile.Publish
Click Publish. Visual Studio builds the Web API project and publishes it to your website.
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.