How to Add Swagger API Documentation in ASP.NET Core

Swagger or OpenAPI describes the standards and specifications for the RESTFul API description. These specifications are an attempt to create a universal and language agnostic description for describing the REST API.

In this article, we shall see below overall aspects,

  • Understanding OpenAPI V3 specification
  • Enabling Swagger Middleware in ASP.NET Core pipeline
  • Enable XML documentation

I found there are slight differences in enabling swagger documentation compare to the old .NET Core 2.x version. These differences often come as surprises until you are already aware of those details.

Certainly below guidelines will also help you if you happen to migrate from .NET Core 2.x version to .NET Core 3.x version in the future.

ASP.NET Core 3.1 uses OpenAPI V3.0 specifications which are more generic guidelines and specifications around how the API documentation should be.

So let’s get started…

Create ASP.NET Core API

Add Swashbuckle.AspNetCore NuGet package

Please add the below Nuget package to your WebAPI using a Command prompt or PMC(package manager console)

PM> Install-Package Swashbuckle.AspNetCore -Version 5.3.3

Note: Your package might be in preview mode. Please update the version to the latest once it is available.

This NuGet package shall add all other required components as shown below and you need not have to add them explicitly,

  • Swashbuckle.AspNetCore.SwaggerUI
  • Swashbuckle.AspNetCore.Swagger
  • Swashbuckle.AspNetCore.SwaggerGen

Update ConfigureServices() method as below,

Add below line to ConfigureServices() method as shown below,

public void ConfigureServices(IServiceCollection services)
         {
             services.AddControllers();
             services.AddSwaggerGen(c =>
             {
                 c.SwaggerDoc("v1", new OpenApiInfo { Title ="MyTestService", Version = "v1", });
              });
         }

Please add the below namespace to use class ‘OpenApiInfo’,

using Microsoft.OpenApi.Models;

Please make a note of the differences between the .NET Core 2.xx version and the 3.0 + version,

Update Configure() method

Add below lin UseSwagger and UseSwaggerUI to Configure() method enabling API pipeline with Swagger capability as shown below,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestService");
            });
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Let’s execute swagger URL,

Enabling XML documentation

Let enable API/method level documentation to our API/Service. Please update the project(.csproj) file as below. The XML file gets created in the output folder itself.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

The above setting will generate the required method-level documentation in the form of an XML file in the project root directory.

Please update the Configure method as below to read this XML file.

Update to Configure method for XML document generation

The updated method as below,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title ="MyTestService", Version = "v1", });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }

The above setting will generate documentation at each method level as below,

The swagger JSON file can be accessed locally via the below route.

https://localhost:44320/swagger/v1/swagger.json

That’s all!

Happy coding !!

Related Posts

Leave a Reply

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