푸터 콘텐츠로 바로가기
.NET 도움말

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

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

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

c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<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");
$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";
$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);
$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;
$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();
$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");
$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");
    }
}
$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);
    }
}
$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.

자주 묻는 질문

ASP.NET Core에서 Swashbuckle을 사용하여 RESTful 웹 API를 문서화하려면 어떻게 해야 하나요?

스와시버클은 코드의 XML 주석에서 스와거 문서를 생성하여 RESTful 웹 API를 문서화하는 데 사용할 수 있습니다. Swashbuckle.AspNetCore 패키지를 설치하고 ASP.NET Core 프로젝트의 `Startup.cs` 파일에서 구성해야 합니다.

새로운 ASP.NET Core 웹 API 프로젝트를 위해 Swashbuckle을 설정하려면 어떤 단계를 거쳐야 하나요?

스와시버클을 설정하려면 먼저 Swashbuckle.AspNetCore NuGet 패키지를 설치합니다. 그런 다음, `Startup.cs` 파일에서 `ConfigureServices` 메서드에 `services.AddSwaggerGen()`을 추가하고 `Configure` 메서드에 `app.UseSwagger()`와 함께 `app.UseSwaggerUI()`를 추가하여 Swagger 미들웨어를 구성합니다.

.NET Core 애플리케이션에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF를 사용하여 .NET Core 애플리케이션에서 HTML 콘텐츠를 PDF로 변환할 수 있습니다. 이 라이브러리를 사용하면 `RenderHtmlAsPdf` 및 `RenderUrlAsPdf`와 같은 메서드를 사용하여 HTML 문자열, 파일 및 URL을 PDF 문서로 변환할 수 있습니다.

API 개발에서 Swashbuckle을 사용하면 어떤 이점이 있나요?

스와시버클은 Swagger 호환 문서를 자동으로 생성하여 API 문서를 간소화하므로 명확하고 일관된 API 문서 표준을 유지하는 데 도움이 됩니다. 또한 Swagger UI를 통해 API를 탐색하고 테스트할 수 있는 사용자 친화적인 인터페이스를 제공합니다.

ASP.NET Core 프로젝트에 PDF 생성 기능을 통합하려면 어떻게 해야 하나요?

ASP.NET Core 프로젝트에 PDF 생성을 통합하는 것은 IronPDF를 사용하여 수행할 수 있습니다. NuGet을 통해 IronPDF 라이브러리를 설치하고 해당 메서드를 사용하여 다양한 콘텐츠 유형에서 PDF를 생성하세요. 프로젝트에 필요한 사용 지시문과 라이선스 키가 포함되어 있는지 확인하세요.

스와시버클에서 Swagger 문서를 사용자 지정하는 데 사용할 수 있는 구성 옵션에는 어떤 것이 있나요?

스와시버클은 API 버전 관리 설정, XML 주석 활성화, 매개변수 명명 규칙 정의, 스와거 UI의 모양과 동작 사용자 지정 등 스와거 문서를 사용자 지정할 수 있는 다양한 구성 옵션을 제공합니다.

ASP.NET Core 프로젝트에서 Swashbuckle을 사용할 때 흔히 발생하는 문제를 해결하려면 어떻게 해야 하나요?

프로젝트 속성에서 XML 문서가 활성화되어 있는지 확인하고, 올바른 패키지 버전을 확인하고, 미들웨어의 적절한 순서를 포함하여 `Startup.cs` 파일에서 올바른 설정을 확인함으로써 Swashbuckle의 일반적인 문제를 해결할 수 있습니다.

C#으로 PDF를 생성하기 위한 IronPDF의 기능은 무엇인가요?

IronPDF는 HTML, URL, ASP.NET 콘텐츠를 PDF로 변환하고, 머리글과 바닥글을 추가하고, PDF를 병합하고, 기존 PDF 파일을 조작하는 등의 기능을 제공합니다. C# 프로젝트에서 PDF 작업을 처리하기 위한 포괄적인 라이브러리입니다.

IronPDF는 상업적 사용을 위한 라이선스를 어떻게 지원하나요?

IronPDF는 상용 라이선스 키를 통한 라이선싱을 지원합니다. 무료 평가판으로 IronPDF를 사용해 보고 프로젝트 구성에 라이선스 키를 포함할 수 있으며, 일반적으로 `appsettings.json` 파일 내 `IronPdf` 섹션 아래에 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.