Zum Fußzeileninhalt springen
.NET HILFE

Swashbuckle ASP .NET Core (Wie es für Entwickler funktioniert)

Swashbuckle is a C# .NET Core NuGet package that helps to automatically document RESTful Web APIs. In this blog, we are going to explore the Swashbuckle ASP.NET Core and IronPDF Installation Instructions NuGet packages, enabling the modern development of ASP.NET Core Web APIs. Together, they provide a host of functionalities that can be achieved with minimal code.

The API documentation pages are displayed using the Swagger UI tool, which uses a swagger.json file generated from the Web API project. The generated JSON document follows the Open API standard. Swashbuckle is available as a NuGet package Swashbuckle.AspNetCore, which, when installed and configured, will automatically expose the Swagger JSON. The Swagger UI tool reads the Swagger JSON file, 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 into an XML documentation file, from which the 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 a Web API project:

dotnet new webapi -n SwashbuckleDemo
cd SwashbuckleDemo
dotnet build
dotnet add package Swashbuckle.AspNetCore --version 6.5.0
dotnet build
dotnet new webapi -n SwashbuckleDemo
cd SwashbuckleDemo
dotnet build
dotnet add package Swashbuckle.AspNetCore --version 6.5.0
dotnet build
SHELL

Here, we create a web API project named "SwashbuckleDemo" and then install the Swashbuckle package to the .NET Core Web API project using the Package Manager Console.

Configure Swagger Middleware

Configure Swagger services in the Startup.cs file.

using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Other service configurations...

        // 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 Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Other service configurations...

        // 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 Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}
Imports System.Reflection
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.AspNetCore.Builder

Public Class Startup
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		' Other service configurations...

		' 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 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
End Class
$vbLabelText   $csharpLabel

Add a controller for todo list APIs:

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

// Example to define an entity class
public class Todo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
}

// Example to define a DbContext class
public class TodoDb : DbContext
{
    public DbSet<Todo> Todos => Set<Todo>();
}

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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.Run();
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

// Example to define an entity class
public class Todo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
}

// Example to define a DbContext class
public class TodoDb : DbContext
{
    public DbSet<Todo> Todos => Set<Todo>();
}

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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.Run();
Imports Microsoft.AspNetCore.Http.HttpResults
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.EntityFrameworkCore
Imports Microsoft.AspNetCore.Mvc
Imports System.Threading.Tasks

' Example to define an entity class
Public Class Todo
	Public Property Id() As Integer
	Public Property Name() As String
	Public Property IsComplete() As Boolean
End Class

' Example to define a DbContext class
Public Class TodoDb
	Inherits DbContext

	Public ReadOnly Property Todos() As DbSet(Of Todo)
		Get
			Return [Set](Of Todo)()
		End Get
	End Property
End Class

Private builder = WebApplication.CreateBuilder(args)
Private app = builder.Build()

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)

app.Run()
$vbLabelText   $csharpLabel

A controller can also be added like below:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
using System.Linq;

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();
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
using System.Linq;

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();
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Logging
Imports System.Collections.Generic
Imports System
Imports System.Linq

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

	Public Class WeatherForecast
		Public Property [Date]() As DateTime
		Public Property TemperatureC() As Integer
		Public Property Summary() As String
	End Class
End Namespace
$vbLabelText   $csharpLabel

The above code is available on GitHub - Swashbuckle Demo.

Swashbuckle offers the 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
$vbLabelText   $csharpLabel

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"
})
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

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()
$vbLabelText   $csharpLabel

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

c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter(Of CustomOperationFilter)()
$vbLabelText   $csharpLabel

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")
$vbLabelText   $csharpLabel

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"
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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()
$vbLabelText   $csharpLabel

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")
$vbLabelText   $csharpLabel

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 Product Overview is the C# PDF Library from Iron Software Website that helps to read and generate PDF documents. It can easily convert formatted documents with style information to PDF. IronPDF can effortlessly generate PDFs from HTML content. It can download the HTML content from a URL and then generate PDFs.

IronPDF is a great tool for converting web pages, URLs, and HTML into PDFs that perfectly replicate the source. It is ideal for generating PDFs of online content such as reports and invoices, and effortlessly creates PDF versions of any webpage.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Installation

Install IronPDF via NuGet using the NuGet Package Manager Details or the Visual Studio Installation Guide 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 IronPDF.

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

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

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 GetWeatherPdf()
        {
            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);
            // Return the PDF file for download
            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 Celsius: {weather.TemperatureC}</p>
    <p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
";
            }
            htmlContent += footer;
            return htmlContent;
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

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 GetWeatherPdf()
        {
            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);
            // Return the PDF file for download
            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 Celsius: {weather.TemperatureC}</p>
    <p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
";
            }
            htmlContent += footer;
            return htmlContent;
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Logging
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq

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 GetWeatherPdf() 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)
			' Return the PDF file for download
			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>
"

			Dim footer = "
</body>
</html>"

			Dim htmlContent = header
			For Each weather In weatherForecasts
				htmlContent &= $"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celsius: {weather.TemperatureC}</p>
    <p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
"
			Next weather
			htmlContent &= footer
			Return htmlContent
		End Function
	End Class

	Public Class WeatherForecast
		Public Property [Date]() As DateTime
		Public Property TemperatureC() As Integer
		Public Property Summary() As String

		Public ReadOnly Property TemperatureF() As Integer
			Get
				Return 32 + CInt(Math.Truncate(TemperatureC / 0.5556))
			End Get
		End Property
	End Class
End Namespace
$vbLabelText   $csharpLabel

Here, we use the weather data to generate an HTML string, which is then used to create a 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 - Swashbuckle Demo Source Code.
The document has a small watermark for trial licenses, removable with a valid license.

Licensing (Free Trial Available)

For the above code to work, a license key is required. Place this key in the appsettings.json file.

{
    "IronPdf": {
        "LicenseKey": "your license key"
    }
}

A trial license is available for developers upon registering with IronPDF Trial Registration. No credit card is needed for a trial license. Register with your email address to obtain a free trial.

Conclusion

Understanding Swashbuckle and IronPDF allows you to effectively integrate API documentation and PDF generation capabilities into your ASP.NET Core applications. IronPDF also offers comprehensive documentation for Getting Started, along with various Code Examples for PDF Generation.

Additionally, you can explore related software products from Iron Software that will help you enhance your coding skills and meet modern application requirements.

Häufig gestellte Fragen

Wie kann ich RESTful Web-APIs in ASP.NET Core mit Swashbuckle dokumentieren?

Swashbuckle kann verwendet werden, um RESTful Web-APIs zu dokumentieren, indem Swagger-Dokumentation aus XML-Kommentaren im Code generiert wird. Sie müssen das Swashbuckle.AspNetCore-Paket installieren und in der `Startup.cs`-Datei Ihres ASP.NET Core-Projekts konfigurieren.

Welche Schritte sind erforderlich, um Swashbuckle für ein neues ASP.NET Core-Web-API-Projekt einzurichten?

Um Swashbuckle einzurichten, installieren Sie zunächst das Swashbuckle.AspNetCore NuGet-Paket. Konfigurieren Sie dann die Swagger-Middleware in der `Startup.cs`-Datei, indem Sie `services.AddSwaggerGen()` in der `ConfigureServices`-Methode und `app.UseSwagger()` zusammen mit `app.UseSwaggerUI()` in der `Configure`-Methode hinzufügen.

Wie kann ich HTML-Inhalte in einer .NET Core-Anwendung in eine PDF-Datei umwandeln?

Sie können HTML-Inhalte in einer .NET Core-Anwendung mit IronPDF in PDF-Dateien umwandeln. Diese Bibliothek ermöglicht es, HTML-Zeichenfolgen, Dateien und URLs mithilfe von Methoden wie `RenderHtmlAsPdf` und `RenderUrlAsPdf` in PDF-Dokumente zu konvertieren.

Was sind die Vorteile der Verwendung von Swashbuckle in der API-Entwicklung?

Swashbuckle vereinfacht die API-Dokumentation durch das automatische Generieren von Swagger-kompatibler Dokumentation, was zur Aufrechterhaltung klarer und konsistenter API-Dokumentationsstandards beiträgt. Es bietet auch eine benutzerfreundliche Oberfläche zur Erkundung und zum Testen von APIs über die Swagger UI.

Wie integriere ich PDF-Generierungsfähigkeiten in ein ASP.NET Core-Projekt?

Die Integration der PDF-Erstellung in ein ASP.NET Core-Projekt kann mit IronPDF erreicht werden. Installieren Sie die IronPDF-Bibliothek über NuGet und verwenden Sie deren Methoden, um PDFs aus verschiedenen Inhaltstypen zu generieren. Stellen Sie sicher, dass Ihr Projekt die erforderlichen using-Direktiven und alle Lizenzschlüssel enthält.

Welche Konfigurationsoptionen stehen zur Anpassung der Swagger-Dokumentation in Swashbuckle zur Verfügung?

Swashbuckle bietet verschiedene Konfigurationsoptionen zur Anpassung der Swagger-Dokumentation, einschließlich der Einstellung der API-Versionsverwaltung, der Aktivierung von XML-Kommentaren, der Definition von Parameternamenskonventionen und der Anpassung des Erscheinungsbildes und Verhaltens der Swagger UI.

Wie kann ich häufig auftretende Probleme beim Einsatz von Swashbuckle in einem ASP.NET Core-Projekt beheben?

Häufige Probleme bei Swashbuckle können behoben werden, indem sichergestellt wird, dass die XML-Dokumentation in den Projekteigenschaften aktiviert ist, die korrekten Paketversionen überprüft und die korrekte Einrichtung in der `Startup.cs`-Datei verifiziert wird, einschließlich der richtigen Reihenfolge der Middleware.

Welche Funktionen bietet IronPDF für die PDF-Generierung in C#?

IronPDF bietet Funktionen wie das Konvertieren von HTML, URLs und ASP.NET-Inhalten in PDFs, das Hinzufügen von Kopf- und Fußzeilen, das Zusammenführen von PDFs und das Manipulieren vorhandener PDF-Dateien. Es ist eine umfassende Bibliothek zur Handhabung von PDF-Operationen in C#-Projekten.

Wie unterstützt IronPDF die Lizenzierung für kommerzielle Nutzung?

IronPDF unterstützt die Lizenzierung durch einen kommerziellen Lizenzschlüssel. Sie können IronPDF mit einer kostenlosen Testversion ausprobieren und den Lizenzschlüssel in Ihrer Projektkonfiguration einbinden, typischerweise innerhalb der `appsettings.json`-Datei unter dem Abschnitt `IronPdf`.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen