.NET幫助 Swashbuckle ASP .NET Core(開發者的工作原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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. API 文件頁面是使用 Swagger UI 工具顯示的,該工具使用從 Web API 專案生成的 swagger.json 文件。 生成的 JSON 文件遵循 Open API 標準。 Swashbuckle 可作為 NuGet 套件 Swashbuckle.AspNetCore 取得,安裝和配置後,將自動暴露 Swagger JSON。 Swagger UI 工具會讀取由 API 上寫的 XML 註解生成的 Swagger JSON 文件。此外,可以通過在專案設置文件中啟用來創建 XML 文檔文件。XML 註解被轉換成 XML 文檔文件,從中生成 Swagger JSON。 然後 Swagger 中間件讀取 JSON 並公開 Swagger JSON 端點。 .NET Core Web API 專案中的實現 我們從一個 Web API 專案開始: 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 在此,我們創建了一個名為 “SwashbuckleDemo” 的 Web API 專案,然後使用套件管理器控制台將 Swashbuckle 套件安裝到 .NET Core Web API 專案中。 配置 Swagger 中間件 在 Startup.cs 文件中配置 Swagger 服務。 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 為待辦事項清單 API 添加控制器: 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 可以像下面這樣添加控制器: 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 上述代碼可以在 GitHub - Swashbuckle Demo 取得。 Swashbuckle 提供以下功能 Swagger UI 工具 Swagger UI 可從 Web API 應用程式的基本 URL 訪問 "/swagger/index.html"。 它列出代碼中的所有 REST API。 Swagger 生成器讀取 JSON 文件並填充 UI。 Swagger JSON Swashbuckle.AspNetCore 自動生成 Swagger JSON 文件,該文件包含有關 API 結構的信息,包括端點、請求和回應類型等詳細信息。 此 JSON 文件可以由支援 Swagger/OpenAPI 標準的其他工具和服務使用。 Swagger JSON 文件可在 Web API 應用程式的基本 URL 下訪問 “/swagger/v1/swagger.json”。 代碼註釋 開發者可以在其 ASP.NET Core 控制器中使用 XML 註釋和屬性,為 Swagger 文檔提供額外信息。 這包括描述、例子和其他增強生成的 Swagger 文檔的元數據。 [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 配置選項 Swashbuckle.AspNetCore 提供多種配置選項用於定制 Swagger 文檔的生成方式。 開發者可以控制哪些 API 被記錄,配置命名約定並調整其他設置。 以下是 Swashbuckle.AspNetCore 提供的一些關鍵配置選項: SwaggerGen 選項 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 這行指定 Swagger 文件版本,並包含 API 的標題和版本等元數據。 c.IncludeXmlComments(xmlPath); c.IncludeXmlComments(xmlPath); c.IncludeXmlComments(xmlPath) $vbLabelText $csharpLabel 此選項允許您從代碼中包含 XML 註釋,以在 Swagger 文檔中提供額外信息。 xmlPath 變量應指向 XML 註釋文件的位置。 c.DescribeAllParametersInCamelCase(); c.DescribeAllParametersInCamelCase(); c.DescribeAllParametersInCamelCase() $vbLabelText $csharpLabel 此選項配置 Swagger 生成器使用小駝峰命名法(camelCase)為參數名稱。 c.OperationFilter<CustomOperationFilter>(); c.OperationFilter<CustomOperationFilter>(); c.OperationFilter(Of CustomOperationFilter)() $vbLabelText $csharpLabel 您可以註冊自定義操作過濾器以修改特定操作的 Swagger 文件。 CustomOperationFilter 是一個實現 IOperationFilter 的類。 Swagger UI 選項 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 這行配置 Swagger UI 以顯示文檔。 第一個參數是 Swagger JSON 文件的 URL,第二個參數是友好的 API 版本名稱。 c.RoutePrefix = "swagger"; c.RoutePrefix = "swagger"; c.RoutePrefix = "swagger" $vbLabelText $csharpLabel 您可以設置 Swagger UI 的路由前綴。 在此示例中,Swagger UI 將可在/swagger 訪問。 c.DocExpansion(DocExpansion.None); c.DocExpansion(DocExpansion.None); c.DocExpansion(DocExpansion.None) $vbLabelText $csharpLabel 此選項控制 Swagger UI 顯示 API 文檔的方式。 DocExpansion.None 預設會折疊所有操作。 SwaggerOptions c.SerializeAsV2 = true; c.SerializeAsV2 = true; c.SerializeAsV2 = True $vbLabelText $csharpLabel 此選項指明是否以 2.0 格式(true)或 3.0 格式(false)序列化 Swagger 文件。 如果要使用 Swagger 2.0,請設置為 true。 c.DisplayOperationId(); c.DisplayOperationId(); c.DisplayOperationId() $vbLabelText $csharpLabel 此選項在 Swagger UI 中顯示操作 ID,對於調試和理解 API 結構很有用。 c.OAuthClientId("swagger-ui"); c.OAuthClientId("swagger-ui"); c.OAuthClientId("swagger-ui") $vbLabelText $csharpLabel 如果您的 API 使用 OAuth 驗證,您可以為 Swagger UI 配置 OAuth 客戶端 ID。 這只是一些可用配置選項的示例。 Swashbuckle.AspNetCore 庫高度可定制,您可以通過組合各種選項和過濾器來調整 Swagger 文檔以滿足您的特定需求。 始終參考官方文檔或在您的開發環境中使用 IntelliSense 以獲取最全新版和詳細的可用選項信息。 Introducing IronPDF IronPDF Product Overview is the C# PDF Library from Iron Software 網站 的 C# PDF 庫,用於讀取和生成 PDF 文件。 它能輕鬆將帶有樣式信息的文檔轉換為 PDF。 IronPDF 可以輕鬆從 HTML 內容生成 PDF。 它可以從 URL 下載 HTML 內容,然後生成 PDF。 IronPDF 是將網頁、URL 和 HTML 轉換為 PDF 的理想工具,能完美複製源內容。 它非常適合生成在線內容如報告和發票的 PDF,並輕鬆創建任何網頁的 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"); } } 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 安裝 Install IronPDF via NuGet using the NuGet Package Manager Details or the Visual Studio 安裝指南 套件管理器控制台。 在套件管理器控制台中輸入指令: Install-Package IronPdf 使用 Visual Studio 現在,讓我們修改應用程式以增加功能,以 PDF 文件格式下載網站內容。 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 在此,我們使用天氣數據生成 HTML 字符串,然後用來創建 PDF 文檔。 HTML 內容 PDF 報告看起來像這樣: 完整代碼可以在 GitHub 上找到 - Swashbuckle Demo 源碼。 文檔上有一個小的試用版水印,可以用有效許可證移除。 許可(可用免費試用) 要使上述代碼運行,需要一個許可證金鑰。 將此密鑰放入 appsettings.json 文件中。 { "IronPdf": { "LicenseKey": "your license key" } } 開發者在 IronPDF 試用註冊 註冊後可獲得試用許可證。 試用許可證不需要信用卡。 用您的電子郵件地址註冊以獲得免費試用。 Conclusion 了解 Swashbuckle 和 IronPDF 使您能夠有效地將 API 文件和 PDF 生成功能集成到 ASP.NET Core 應用程式中。 IronPDF also offers comprehensive documentation for Getting Started, along with various Code Examples for PDF Generation. 此外,您還可以探索 Iron Software 提供的相關軟件產品,這將有助於提升您的編碼技能並滿足現代應用程式需求。 常見問題解答 如何在 ASP.NET Core 中使用 Swashbuckle 為 RESTful Web API 編寫文檔? Swashbuckle 可以通過從代碼中的 XML 註釋生成 Swagger 文檔來記錄 RESTful Web API。您需要安裝 Swashbuckle.AspNetCore 包並在 ASP.NET Core 項目的 `Startup.cs` 文件中進行配置。 在新的 ASP.NET Core Web API 項目中設置 Swashbuckle 涉及哪些步驟? 要設置 Swashbuckle,首先安裝 Swashbuckle.AspNetCore NuGet 包。接下來,在 `Startup.cs` 文件中配置 Swagger 中間件,在 `ConfigureServices` 方法中添加 `services.AddSwaggerGen()`,並在 `Configure` 方法中添加 `app.UseSwagger()` 和 `app.UseSwaggerUI()`。 如何在 .NET Core 應用程序中將 HTML 內容轉換為 PDF? 可以在 .NET Core 應用程序中使用 IronPDF 將 HTML 內容轉換為 PDF。該庫允許您使用 `RenderHtmlAsPdf` 和 `RenderUrlAsPdf` 等方法將 HTML 字符串、文件和 URL 轉換為 PDF 文檔。 在 API 開發中使用 Swashbuckle 有哪些好處? Swashbuckle 通過自動生成符合 Swagger 的文檔簡化了 API 文檔,這有助於維護清晰一致的 API 文檔標準。它還提供了一個用户友好的界面,通過 Swagger UI 探索和測試 API。 如何在 ASP.NET Core 項目中集成 PDF 生成功能? 可以通过使用 IronPDF 来在 ASP.NET Core 项目中集成 PDF 生成。通过 NuGet 安装 IronPDF 库,并使用其方法从各种内容类型生成 PDF。确保您的项目包含必要的 using 語句和任何许可密钥。 Swashbuckle 提供了哪些配置选项来定制 Swagger 文档? Swashbuckle 提供了多種配置选项来定制 Swagger 文档,包括設置 API 版本控制、啟用 XML 註釋、定義參數命名約定,以及定制 Swagger UI 的外觀和行為。 在使用 Swashbuckle 的 ASP.NET Core 项目中,如何排除常见问题的故障? 可以通过确保在項目屬性中啟用 XML 文檔、檢查正確的包版本,以及在 `Startup.cs` 文件中驗證正確的設置,包括中間件的正確順序來解決 Swashbuckle 的常見問題。 IronPDF 在 C# 中生成 PDF 有哪些特性? IronPDF 提供了將 HTML、URL 和 ASP.NET 內容轉換成 PDF、添加標頭和頁腳、合併 PDF 以及操縱現有 PDF 文件等功能。它是處理 C# 專案中 PDF 操作一個綜合性的程式庫。 IronPDF 如何支持商業用途的授權? IronPDF 通過商業許可密鑰支持授權。您可以通過免費試用測試 IronPDF,並將授權密鑰包含在您的項目配置中,通常位於 `appsettings.json` 檔案中的 `IronPdf` 区域。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# Stopwatch(開發者的工作原理)NPlot C#(開發者的工作原理)