Swashbuckle ASP .NET Core (How It Works For Developer)

Introduction

Swashbuckle is a C# .NET core NuGet package which helps to automatically document the RESTful Web APIs developed. In this blog, we are going to explore Swashbuckle ASP.NET core and IronPDF NuGet packages, which will enable modern application development of ASP.NET Core Web API. Together they enable a host of functionality which can be achieved with minimal amount of code.

The API documentation pages are displayed using swagger UI tool which uses swagger.json which is generated from the web API project. The generated JSON document follows the open API standard. The Swashbuckle is available as NuGget package Swashbuckle.AspNetCore which when installed and configured, will automatically expose swagger JSON. The swagger UI tool reads the swagger JSON file, which is generated from XML comments written on the APIs. Additionally, an XML documentation file can be created by enabling it in the project settings file. XML comments are converted to an XML documentation file, from which swagger JSON is generated. Then the swagger middleware reads the JSON and exposes swagger JSON endpoints.

Implementation in .NET Core Web API project

Let us start with Web API project

dotnet new webapi -n SwashbuckleDemo
cd Swashbuckle
dotnet build
dotnet add package --version 6.5.0 Swashbuckle.AspNetCore
dotnet build
dotnet new webapi -n SwashbuckleDemo
cd Swashbuckle
dotnet build
dotnet add package --version 6.5.0 Swashbuckle.AspNetCore
dotnet build
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet New webapi -n SwashbuckleDemo cd Swashbuckle dotnet build dotnet add package --version 6.5.0 Swashbuckle.AspNetCore dotnet build
VB   C#

Here we are creating a web API project "SwashbuckleDemo" and then install package swashbuckle to .NET Core Web API project from Package Manager Console.

Configure Swagger Middleware

Configure Swagger services in the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations...
    // swagger ui components 
    // Register the Swagger generator
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        // Optionally, include XML comments for additional information
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other app configurations...
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    // Enable static file middleware to serve Swagger UI (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
}
public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations...
    // swagger ui components 
    // Register the Swagger generator
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        // Optionally, include XML comments for additional information
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other app configurations...
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    // Enable static file middleware to serve Swagger UI (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Other service configurations...
	' swagger ui components 
	' Register the Swagger generator
	services.AddSwaggerGen(Sub(c)
		c.SwaggerDoc("v1", New OpenApiInfo With {
			.Title = "My API",
			.Version = "v1"
		})
		' Optionally, include XML comments for additional information
		Dim xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"
		Dim xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile)
		c.IncludeXmlComments(xmlPath)
	End Sub)
End Sub
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
	' Other app configurations...
	' Enable middleware to serve generated Swagger as a JSON endpoint.
	app.UseSwagger()
	' Enable static file middleware to serve Swagger UI (HTML, JS, CSS, etc.),
	' specifying the Swagger JSON endpoint.
	app.UseSwaggerUI(Sub(c)
		c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")
	End Sub)
End Sub
VB   C#

Also add a controller for todo list APIs

app.MapGet("/", () => "SwashbuckleDemo!");
app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
        ? Results.Ok(todo)
        : Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();
    return Results.Created($"/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();
    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }
    return Results.NotFound();
});
app.MapGet("/", () => "SwashbuckleDemo!");
app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
        ? Results.Ok(todo)
        : Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();
    return Results.Created($"/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();
    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }
    return Results.NotFound();
});
app.MapGet("/", Function() "SwashbuckleDemo!")
app.MapGet("/todoitems", Async Function(db As TodoDb) Await db.Todos.ToListAsync())
app.MapGet("/todoitems/complete", Async Function(db As TodoDb) Await db.Todos.Where(Function(t) t.IsComplete).ToListAsync())
Dim tempVar As Boolean = TypeOf db.Todos.FindAsync(id) Is Todo
Dim todo As Todo = If(tempVar, CType(db.Todos.FindAsync(id), Todo), Nothing)
app.MapGet("/todoitems/{id}", Async Function(id As Integer, db As TodoDb)If(Await tempVar, Results.Ok(todo), Results.NotFound()))
app.MapPost("/todoitems", Async Function(todo As Todo, db As TodoDb)
	db.Todos.Add(todo)
	Await db.SaveChangesAsync()
	Return Results.Created($"/todoitems/{todo.Id}", todo)
End Function)
app.MapPut("/todoitems/{id}", Async Function(id As Integer, inputTodo As Todo, db As TodoDb)
	Dim todo = Await db.Todos.FindAsync(id)
	If todo Is Nothing Then
		Return Results.NotFound()
	End If
	todo.Name = inputTodo.Name
	todo.IsComplete = inputTodo.IsComplete
	Await db.SaveChangesAsync()
	Return Results.NoContent()
End Function)
app.MapDelete("/todoitems/{id}", Async Function(id As Integer, db As TodoDb)
	Dim tempVar2 As Boolean = TypeOf db.Todos.FindAsync(id) Is Todo
	Dim todo As Todo = If(tempVar2, CType(db.Todos.FindAsync(id), Todo), Nothing)
	If Await tempVar2 Then
		db.Todos.Remove(todo)
		Await db.SaveChangesAsync()
		Return Results.Ok(todo)
	End If
	Return Results.NotFound()
End Function)
VB   C#

A controller can also be added like below:

using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
}
using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
}
Imports Microsoft.AspNetCore.Mvc
Namespace RestFullMinimalApi.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class WeatherForecastController
		Inherits ControllerBase

		Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }
		Private ReadOnly _logger As ILogger(Of WeatherForecastController)
		Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
			_logger = logger
		End Sub
		''' <summary>
		''' Retrieves WeatherForecast
		''' </summary>
		''' <remarks>Awesomeness!</remarks>
		''' <response code="200">Retrieved</response>
		''' <response code="404">Not found</response>
		''' <response code="500">Oops! Can't lookup your request right now</response>
		<HttpGet(Name := "GetWeatherForecast")>
		Public Function [Get]() As IEnumerable(Of WeatherForecast)
			Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			}).ToArray()
		End Function
	End Class
End Namespace
VB   C#

The above code is available on GitHub.

Swashbuckle offers following features

Swagger UI tool

Swashbuckle ASP .NET Core (How It Works For Developer): Figure 1 - Swagger UI tool

Swagger UI is available at "/swagger/index.html" from the base URL of the Web API application. It lists all the REST APIs from the code. The swagger generator reads the JSON file and populates the UI.

Swagger JSON

Swashbuckle.AspNetCore automatically generates the Swagger JSON file, which contains information about the API's structure, including details such as endpoints, request and response types, and more. This JSON file can be used by other tools and services that support the Swagger/OpenAPI standard.

The swagger JSON file is available at "/swagger/v1/swagger.json" from the base URL of the web API application.

Swashbuckle ASP .NET Core (How It Works For Developer): Figure 2 - The swagger JSON file.

Code Annotations

Developers can use XML comments and attributes within their ASP.NET Core controllers to provide additional information for swagger documentation. This includes descriptions, examples, and other metadata that enhances the generated Swagger documentation.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
}
<ApiController>
<Route("[controller]")>
Public Class WeatherForecastController
	Inherits ControllerBase

	Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }
	Private ReadOnly _logger As ILogger(Of WeatherForecastController)
	Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
		_logger = logger
	End Sub
	''' <summary>
	''' Retrieves WeatherForecast
	''' </summary>
	''' <remarks>Awesomeness!</remarks>
	''' <response code="200">Retrieved</response>
	''' <response code="404">Not found</response>
	''' <response code="500">Oops! Can't lookup your request right now</response>
	<HttpGet(Name := "GetWeatherForecast")>
	Public Function [Get]() As IEnumerable(Of WeatherForecast)
		Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
			.Date = DateTime.Now.AddDays(index),
			.TemperatureC = Random.Shared.Next(-20, 55),
			.Summary = Summaries(Random.Shared.Next(Summaries.Length))
		}).ToArray()
	End Function
End Class
VB   C#

Configuration Options

Swashbuckle.AspNetCore provides various configuration options to customize how Swagger documentation is generated. Developers can control which APIs are documented, configure naming conventions, and adjust other settings.

Here are some of the key configuration options provided by Swashbuckle.AspNetCore:

SwaggerGen Options

c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SwaggerDoc("v1", New OpenApiInfo With {
	.Title = "My API",
	.Version = "v1"
})
VB   C#

This line specifies the Swagger document version and includes metadata such as the title and version of your API.

c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath)
VB   C#

This option allows you to include XML comments from your code to provide additional information in the Swagger documentation. The xmlPath variable should point to the location of your XML comments file.

c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase()
VB   C#

This option configures the Swagger generator to use camel Case for parameter names.

c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter(Of CustomOperationFilter)()
VB   C#

You can register custom operation filters to modify the Swagger documentation for specific operations. CustomOperationFilter is a class that implements IOperationFilter.

Swagger UI Options

c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")
VB   C#

This line configures the Swagger UI to display documentation. The first parameter is the URL of the Swagger JSON file, and the second parameter is a user-friendly name for the API version.

c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger"
VB   C#

You can set the route prefix for the Swagger UI. In this example, the Swagger UI will be available at /swagger.

c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None)
VB   C#

This option controls how the Swagger UI displays the API documentation. DocExpansion.None collapses all the operations by default.

SwaggerOptions

c.SerializeAsV2 = true;
c.SerializeAsV2 = true;
c.SerializeAsV2 = True
VB   C#

This option specifies whether to serialize the Swagger document in version 2.0 format (true) or 3.0 format (false). Set it to true if you want to use Swagger 2.0.

c.DisplayOperationId();
c.DisplayOperationId();
c.DisplayOperationId()
VB   C#

This option displays the operation ID in the Swagger UI, which can be useful for debugging and understanding the structure of your API.

c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui")
VB   C#

If your API uses OAuth authentication, you can configure the OAuth client ID for Swagger UI.

These are just a few examples of the configuration options available. The Swashbuckle.AspNetCore library is highly customizable, and you can tailor the Swagger documentation to meet your specific needs by combining various options and filters. Always refer to the official documentation or IntelliSense in your development environment for the most up-to-date and comprehensive information on available options.

Introducing IronPDF

IronPDF is the C# PDF Library from IronSoftware that helps to read and generate PDF docs. It can easily convert formatted documents with style information to PDF. IronPDF can easily generate PDFs from HTML content. It can download the HTML content from the URL and then generate PDFs.

Installation

IronPDF can be installed using NuGet Package Manager or using the Visual Studio Package Manager Console.

In the Package Manager Console, input the command:

Install-Package IronPdf

Using Visual Studio

Swashbuckle ASP .NET Core (How It Works For Developer): Figure 3 - Open your project in Visual Studio. Go to the "Tools" menu, select "NuGet Package Manager", then select "Manage NuGet Packages for Solution". In the NuGet Package Manager interface, search for the package "ironpdf" in the Browse tab. Then select and install the latest version of the IronPDF.

Now, let us modify our application to add functionality to download a website content as a PDF file.

using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
    /// <summary>
    /// Retrieves WeatherForecast as Pdf
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet("download", Name = "DownloadWeatherForecast")]
    public IActionResult GetWeatherExcel()
    {
        var results = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        }).ToArray();
        var html = GetHtml(results);
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(html);
        var fileName = "WeatherReport.pdf";
        PDF.SaveAs(fileName);
        var stream = new FileStream(fileName, FileMode.Open);
        // Save the excel file
        return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName };
    }
    private static string GetHtml(WeatherForecast[] weatherForecasts)
    {
        string header = $@"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
    ";
        var footer = @"
</body>
</html>";
        var htmlContent = header;
        foreach (var weather in weatherForecasts)
        {
            htmlContent += $@"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celcius: {weather.TemperatureC}</p>
    <p>Temperature in Farenheit: {weather.TemperatureF}</p>
";
        }
        htmlContent += footer;
        return htmlContent;
    }
}
using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
    /// <summary>
    /// Retrieves WeatherForecast as Pdf
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet("download", Name = "DownloadWeatherForecast")]
    public IActionResult GetWeatherExcel()
    {
        var results = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        }).ToArray();
        var html = GetHtml(results);
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(html);
        var fileName = "WeatherReport.pdf";
        PDF.SaveAs(fileName);
        var stream = new FileStream(fileName, FileMode.Open);
        // Save the excel file
        return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName };
    }
    private static string GetHtml(WeatherForecast[] weatherForecasts)
    {
        string header = $@"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
    ";
        var footer = @"
</body>
</html>";
        var htmlContent = header;
        foreach (var weather in weatherForecasts)
        {
            htmlContent += $@"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celcius: {weather.TemperatureC}</p>
    <p>Temperature in Farenheit: {weather.TemperatureF}</p>
";
        }
        htmlContent += footer;
        return htmlContent;
    }
}
Imports Microsoft.AspNetCore.Mvc
Namespace RestFullMinimalApi.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class WeatherForecastController
		Inherits ControllerBase

		Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }
		Private ReadOnly _logger As ILogger(Of WeatherForecastController)
		Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
			_logger = logger
		End Sub
		''' <summary>
		''' Retrieves WeatherForecast
		''' </summary>
		''' <remarks>Awesomeness!</remarks>
		''' <response code="200">Retrieved</response>
		''' <response code="404">Not found</response>
		''' <response code="500">Oops! Can't lookup your request right now</response>
		<HttpGet(Name := "GetWeatherForecast")>
		Public Function [Get]() As IEnumerable(Of WeatherForecast)
			Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			}).ToArray()
		End Function
		''' <summary>
		''' Retrieves WeatherForecast as Pdf
		''' </summary>
		''' <remarks>Awesomeness!</remarks>
		''' <response code="200">Retrieved</response>
		''' <response code="404">Not found</response>
		''' <response code="500">Oops! Can't lookup your request right now</response>
		<HttpGet("download", Name := "DownloadWeatherForecast")>
		Public Function GetWeatherExcel() As IActionResult
			Dim results = Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			}).ToArray()
			Dim html = GetHtml(results)
			Dim Renderer = New ChromePdfRenderer()
			Dim PDF = Renderer.RenderHtmlAsPdf(html)
			Dim fileName = "WeatherReport.pdf"
			PDF.SaveAs(fileName)
			Dim stream = New FileStream(fileName, FileMode.Open)
			' Save the excel file
			Return New FileStreamResult(stream, "application/octet-stream") With {.FileDownloadName = fileName}
		End Function
		Private Shared Function GetHtml(ByVal weatherForecasts() As WeatherForecast) As String
			Dim header As String = $"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
    "
	ignore ignore ignore ignore ignore var footer = "
</body>
</html>"
	ignore ignore var htmlContent = header
			For Each weather In weatherForecasts
				htmlContent += $"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celcius: {weather.TemperatureC}</p>
    <p>Temperature in Farenheit: {weather.TemperatureF}</p>
"
	ignore ignore ignore ignore ignore
			Next weather
			htmlContent += footer
			Return htmlContent
		End Function
	End Class
End Namespace
VB   C#

Here we are using the weather data to generate an HTML string and then this string is used to generate the PDF document.

HTML Content

Swashbuckle ASP .NET Core (How It Works For Developer): Figure 4 - HTML content for Weather Forecast.

And the PDF report looks like this:

Swashbuckle ASP .NET Core (How It Works For Developer): Figure 5 - HTML to PDF Output file: WeatherReport.pdf

The entire code can be found on GitHub here.
The document has a small watermark for trial licenses and can be removed using a valid license.

Licensing (Free Trial Available)

For the above code to work, a license key is required. This key needs to be placed in the appsettings.json file.

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

A trial license is available for developers upon registering here and yes, no credit card is needed for a trial license. One can provide the email address and register for a free trial.

Conclusion

Swashbuckle. IronPDF also offers a proper documentation on how to get started, along with various code examples.

Also, you can explore additional software products from Iron Software which will help you improve your coding skills and achieve modern application requirements.