.NET幫助 Swashbuckle ASP .NET Core(開發者的工作原理) Jacob Mellor 更新:2025年7月28日 下載 IronPDF NuGet 下載 DLL 下載 Windows Installer 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 Swashbuckle 是一個 C# .NET Core NuGet 套件,可幫助自動記錄 RESTful Web API。在此博客中,我們將探討 Swashbuckle ASP.NET Core 和 IronPDF 安裝說明 NuGet 套件,使 ASP.NET Core Web API 的現代開發成為可能。結合這兩者,可以通過最少的代碼實現多種功能。 API 文檔頁面使用 Swagger UI 工具顯示,該工具使用從 Web API 專案中生成的 swagger.json 文件。 生成的 JSON 文件符合 Open API 標準。 Swashbuckle 以 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"); }); } } $vbLabelText $csharpLabel 為待辦事項清單 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 可以如下添加控制器: 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 上述代碼可在 GitHub - Swashbuckle Demo 上找到。 Swashbuckle 提供以下功能 Swagger UI 工具 Swagger UI 可在 Web API 應用程序的基礎 URL 的 "swagger/index.html" 中找到。 它列出了來自代碼的所有 REST APIs。 Swagger 生成器讀取 JSON 文件並填充 UI。 Swagger JSON Swashbuckle.AspNetCore 自動生成 Swagger JSON 文件,其中包含關於 API 結構的信息,包括端點、請求和回應類型等細節。 其他支持 Swagger/OpenAPI 標準的工具和服務可以使用此 JSON 文件。 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(); } } $vbLabelText $csharpLabel 配置選項 Swashbuckle.AspNetCore 提供多種配置選項以定制 Swagger 文檔的生成方式。 開發者可以控制哪些 APIs 被記錄下來,配置命名約定,並調整其他設置。 以下是 Swashbuckle.AspNetCore 提供的一些關鍵配置選項: SwaggerGen 選項 c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); $vbLabelText $csharpLabel 此行指定 Swagger 文檔版本並包含元數據,例如 API 的標題和版本。 c.IncludeXmlComments(xmlPath); c.IncludeXmlComments(xmlPath); $vbLabelText $csharpLabel 此選項允許您包含代碼中的 XML 註釋,以在 Swagger 文檔中提供額外的信息。 xmlPath 變量應指向您的 XML 註釋文件的位置。 c.DescribeAllParametersInCamelCase(); c.DescribeAllParametersInCamelCase(); $vbLabelText $csharpLabel 此選項配置 Swagger 生成器使用小駝峰式大小寫作為參數名稱。 c.OperationFilter<CustomOperationFilter>(); c.OperationFilter<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"); $vbLabelText $csharpLabel 此行配置 Swagger UI 以顯示文檔。 第一個參數是 Swagger JSON 文件的 URL,第二個參數是 API 版本的用戶友好名稱。 c.RoutePrefix = "swagger"; c.RoutePrefix = "swagger"; $vbLabelText $csharpLabel 您可以設置 Swagger UI 的路由前綴。 在此範例中,Swagger UI 將可在 /swagger 處取得。 c.DocExpansion(DocExpansion.None); c.DocExpansion(DocExpansion.None); $vbLabelText $csharpLabel 此選項控制 Swagger UI 如何顯示 API 文檔。 DocExpansion.None 默認情況下會折疊所有操作。 SwaggerOptions c.SerializeAsV2 = true; c.SerializeAsV2 = true; $vbLabelText $csharpLabel 此選項指定是將 Swagger 文檔序列化為版本 2.0 格式 (true) 還是版本 3.0 格式 (false)。 如果您想使用 Swagger 2.0,請將其設成 true。 c.DisplayOperationId(); c.DisplayOperationId(); $vbLabelText $csharpLabel 此選項在 Swagger UI 中顯示操作 ID,這對於調試和理解您的 API 結構非常有用。 c.OAuthClientId("swagger-ui"); c.OAuthClientId("swagger-ui"); $vbLabelText $csharpLabel 如果您的 API 使用 OAuth 驗證,您可以為 Swagger UI 配置 OAuth 客戶端 ID。 這只是幾個可用的配置選項的例子。 Swashbuckle.AspNetCore 程式庫具有高度的自定義能力,您可以通過結合多種選項和濾波器來調整 Swagger 文檔以滿足您的特定需求。 始終查閱官方文檔或在開發環境中使用 IntelliSense 以獲得最 的最新和完整的選項信息。 介紹 IronPDF IronPDF 產品概覽是 Iron Software 官網 使用的 C# PDF 程式庫,有助於讀取和生成 PDF 文件。 它可以輕鬆將帶有樣式信息的格式文件轉換為 PDF。 IronPDF 可輕鬆從 HTML 內容生成 PDF。 它可以從 URL 下載 HTML 內容,然後生成 PDF。 IronPDF 是將網頁、網址和 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"); } } $vbLabelText $csharpLabel 安裝 通過 NuGet 安裝 IronPDF,使用 NuGet 套件管理器詳細信息 或 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); } } $vbLabelText $csharpLabel 在這裡,我們使用天氣數據生成 HTML 字串,然後使用這些字串來創建 PDF 文件。 HTML 內容 PDF 報告看起來像這樣: 整個代碼可以在 GitHub 上找到 - Swashbuckle Demo 資源代碼。 該文件在試用許可證下帶有一個小的水印,可用有效的許可證移除。 授權(提供免費試用) 要使上述代碼正常工作,需要授權金鑰。 將此金鑰放置在 appsettings.json 文件中。 { "IronPdf": { "LicenseKey": "your license key" } } 開發人員可以在註冊 IronPDF 試用註冊 後獲得試用許可證。 試用許可證不需要信用卡。 使用您的電子郵件地址註冊以獲得免費試用。 結論 了解 Swashbuckle 和 IronPDF 後,您可以將 API 文檔和 PDF 生成功能有效整合到您的 ASP.NET Core 應用程式中。 IronPDF 還提供 入門指南的詳細文檔,以及各種 使用 HTML 創建 PDF 的代碼範例。 此外,您還可以探索 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` 区域。 Jacob Mellor 立即與工程團隊聊天 首席技術官 Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。 相關文章 更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新2025年12月20日 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# Stopwatch(開發者的工作原理)NPlot C#(開發者的工作原理)
更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多