Home » Web API » How to Add Swagger in Web API .net core manually? – easy guide

How to Add Swagger in Web API .net core manually? – easy guide

Swagger is a powerful tool for documenting and testing APIs in a user-friendly and interactive way. It allows developers to create interactive API documentation, making it easier for both developers and consumers to understand and interact with the API. While there are tools and packages that automate Swagger integration in .NET Core, sometimes you may want to implement it manually for more control over the configuration and customization. In this article, we will guide you through the manual implementation of Swagger in a .NET Core application.


Swagger implementation in .NET Core Web API Project

The following steps describe the configuration of Swagger docs in the Web API project.

Step 1: Install Required Packages

To begin, open your .NET Core project in Visual Studio or Visual Studio Code and install the necessary NuGet packages for Swagger integration. You need Swashbuckle.AspNetCore package. You can install these packages using the NuGet Package Manager or Package Manager Console:

option 1) Console Command


dotnet add package Swashbuckle.AspNetCore


dotnet add package swashbuckle asp .net core

Note: This command will add all packages available under Swashbuckle.AspNetCore.
Recommendation – Install only necessary packages from Nuget Manager


option 2) Nuget Package manager recommended

You can install only the required packages needed for Swagger Web API documentation from Nuget Package Manager

swagger aspnetcore nuget package


Step 2: Configure Swagger in Startup.cs

Open your project’s Startup.cs file, where you configure your application’s services and middleware. Add the following code to configure Swagger:

using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Reflection;


public void ConfigureServices(IServiceCollection services)
{
	// ...

	services.AddSwaggerGen(swagger =>
	{
		//This is to generate the Default UI of Swagger Documentation  
		swagger.SwaggerDoc("v1", new OpenApiInfo
		{
			Version = "v1",
			Title = "My App",
			Description = "About Application"
		});

		// Set the comments path for the Swagger JSON and UI.
		var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
		var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
		swagger.IncludeXmlComments(xmlPath);                
	});
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	// ...

	// Enable middleware to serve generated Swagger as a JSON endpoint.
	app.UseSwagger();

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

In the code above, you are configuring Swagger in the ConfigureServices and Configure methods of your Startup.cs file. Make sure to replace “Your API Name” with the actual name of your API.



Step 3: Define API Documentation

Now, let’s add documentation to your API endpoints. Decorate your controllers and actions with XML comments that Swagger will use to generate documentation. For example:

/// <summary>
/// This is a sample controller for managing products.
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
    /// <summary>
    /// Gets a list of all WeatherForecast.
    /// </summary>
    /// <returns>A list of WeatherForecast.</returns>
    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        // Your action code here
    }
    // Add similar XML comments for other actions
} 

After adding descriptions to the APIs, go to the Swagger URL and check the documentation.


Step 4: Generate Swagger Documentation

With the configuration and documentation in place, you can now generate Swagger documentation by running your application. Build and run your .NET Core application, and navigate to URL https://localhost:<port>/swagger or https://localhost:<port>/swagger/index.html in your browser. You should see the Swagger UI, where you can interactively explore and test your API.

swagger api documentation sample


If you want to launch the Swagger URL by default then change the value of launchUrl in launchSettings.json file, See the screenshot below:

launch swagger default setting


Troubleshooting

You might get System.IO.FileNotFoundException error – “Could not find file ‘filePath/appfilename.xml‘” as shown in the below screenshot.

XML comments file could not be found – Swagger
xml comments file could not be found

In such case, you can enable DocumentationFile property, manually. There are two ways to do it:

Option 1) Go to .csproj project file and add the GenerateDocumentationFile tag within PropertyGroup:

.csproj – file
<PropertyGroup>
	<GenerateDocumentationFile>true</GenerateDocumentationFile> 
</PropertyGroup>

Option 2) If you want to avoid editing the .csproj manually then right-click on app >> click on Properties >> Select Build and tick XML documentation file checkbox under the output section. See the screenshot below:

xml documentation file cjproj property

It will add the DocumentationFile tag in PropertyGroup automatically.

.csproj – file
documentation file property tag

Leave a Reply

Your email address will not be published. Required fields are marked *