OpenAPI .NET(對於開發者的運行原理)
OpenAPI,以前稱為Swagger,是用於構建和描述RESTful API的規範。它允許開發人員以標準化格式定義API的結構,使各種工具和服務能夠有效地理解和互動REST API並提供反饋。 在.NET生態系統中,OpenAPI .NET整合通過多個庫和工具來促進,使建立、記錄和使用API變得更加容易。
在這篇文章中,我們將了解OpenAPI支持規範以及如何使用IronPDF建立PDF文件並將其作為API呼叫響應返回。
在.NET中設置OpenAPI
要開始OpenAPI .NET項目,您通常會使用Swashbuckle庫,它為您的ASP.NET Core API生成OpenAPI規範或文件。
步驟1:安裝Swashbuckle
首先,您需要通過Visual Studio中的NuGet安裝Swashbuckle.AspNetCore包。 您可以使用NuGet包管理器控制台來完成此操作:
Install-Package Swashbuckle.AspNetCore
也可以使用.NET CLI:
dotnet add package Swashbuckle.AspNetCore
dotnet add package Swashbuckle.AspNetCore
步驟2:配置Swashbuckle
接下來,您需要在ASP.NET Core項目中配置Swashbuckle。 這涉及更新Program.cs文件以新增Swagger服務和配置Swagger中介軟體。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Configures Swagger/OpenAPI descriptions.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Configures Swagger/OpenAPI descriptions.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Dim builder = WebApplication.CreateBuilder(args)
' Add services to the container.
builder.Services.AddControllers()
' Configures Swagger/OpenAPI descriptions.
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()
Dim app = builder.Build()
' Configure the HTTP request pipeline.
If app.Environment.IsDevelopment() Then
app.UseSwagger()
app.UseSwaggerUI()
End If
app.UseHttpsRedirection()
app.UseAuthorization()
app.MapControllers()
app.Run()
生成和查看API文件
一旦配置Swashbuckle,運行您的應用程式將自動生成OpenAPI文件。 您可以通過導航到Swagger UI介面來查看這些OpenAPI描述。
使用OpenAPI定義
OpenAPI定義是強大的工具,可用於生成客戶端SDK、測試API、並確保跨不同服務的一致性。 OpenAPI規範定義了一個標準、語言中立的API介面,允許人和計算機在無需存取源程式碼的情況下瞭解服務的功能。
使用自定義註釋擴展OpenAPI
Swashbuckle允許您通過自定義註釋增強您的OpenAPI文件。 這些註釋可以直接新增到您的控制器和模型中,以提供關於API行為和資料結構的附加資訊。
範例:自定義註釋
using Microsoft.AspNetCore.Mvc;
namespace WebApplication8.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;
}
[HttpGet(Name = "GetWeatherForecast")]
[SwaggerOperation(Summary = "Gets the weather forecast for the next 5 days")]
[SwaggerResponse(200, "Successfully retrieved weather forecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
using Microsoft.AspNetCore.Mvc;
namespace WebApplication8.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;
}
[HttpGet(Name = "GetWeatherForecast")]
[SwaggerOperation(Summary = "Gets the weather forecast for the next 5 days")]
[SwaggerResponse(200, "Successfully retrieved weather forecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Imports Microsoft.AspNetCore.Mvc
Namespace WebApplication8.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
<HttpGet(Name := "GetWeatherForecast")>
<SwaggerOperation(Summary := "Gets the weather forecast for the next 5 days")>
<SwaggerResponse(200, "Successfully retrieved weather forecast")>
Public Function [Get]() As IEnumerable(Of WeatherForecast)
Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
.Date = DateTime.Now.AddDays(index),
.TemperatureC = Random.Shared.Next(-20, 55),
.Summary = Summaries(Random.Shared.Next(Summaries.Length))
}).ToArray()
End Function
End Class
End Namespace
在此範例中,使用SwaggerResponse屬性來為端點提供詳細的OpenAPI描述和響應碼。
輸出

點擊執行按鈕,您將獲得以下響應。

IronPDF
IronPDF for ASP.NET 是一個強大的工具,能夠在ASP.NET應用程式中無縫地生成和操作PDF文件。 憑藉其直觀的API和強大的功能,開發人員可以輕鬆地將PDF生成整合到其網路項目中,為使用者提供增強的文件管理能力。 無論是從頭建立PDF、將HTML內容轉換為PDF,還是新增圖像和文字等動態元素,IronPDF簡化了過程,確保高效和專業的文件生成。
使用NuGet包管理器安裝的步驟:
- 在Visual Studio中打開您的ASP.NET項目,然後前往"工具"選單。
- 選擇"NuGet包管理器",然後點擊"管理解決方案的NuGet包"。
- 在"瀏覽"標籤中,搜尋"IronPDF"並選擇所需的版本。 點擊"安裝"以將包新增到您的項目中。 IronPDF及其依賴項將自動下載並整合,允許您在ASP.NET應用程式中無縫利用其功能。

在API呼叫中獲取PDF文件
將以下程式碼新增到您的控制器文件中,它使用IronPDF建立PDF文件並將其作為API呼叫的回應返回。
using Microsoft.AspNetCore.Mvc;
using IronPdf;
namespace WebApplication8.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;
}
[HttpGet(Name = "GetWeatherForecast")]
public IActionResult GetWeatherForecastPdf()
{
var htmlContent = @"
<html>
<head>
<title>Weather Forecast</title>
</head>
<body>
<h1>Weather Forecast</h1>
<table>
<tr>
<th>Date</th>
<th>Temperature (Celsius)</th>
<th>Summary</th>
</tr>";
var forecasts = 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)]
});
// Iterate over the forecasts and add data to the HTML string
foreach (var forecast in forecasts)
{
htmlContent += $@"
<tr>
<td>{forecast.Date.ToShortDateString()}</td>
<td>{forecast.TemperatureC}</td>
<td>{forecast.Summary}</td>
</tr>";
}
htmlContent += @"
</table>
</body>
</html>";
// Convert the HTML string to a PDF using IronPDF
var renderer = new ChromePdfRenderer();
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
// Retrieve the byte array of the generated PDF
var pdfBytes = pdfDocument.BinaryData;
// Return the PDF file to the client
return File(pdfBytes, "application/pdf", "WeatherForecast.pdf");
}
}
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;
namespace WebApplication8.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;
}
[HttpGet(Name = "GetWeatherForecast")]
public IActionResult GetWeatherForecastPdf()
{
var htmlContent = @"
<html>
<head>
<title>Weather Forecast</title>
</head>
<body>
<h1>Weather Forecast</h1>
<table>
<tr>
<th>Date</th>
<th>Temperature (Celsius)</th>
<th>Summary</th>
</tr>";
var forecasts = 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)]
});
// Iterate over the forecasts and add data to the HTML string
foreach (var forecast in forecasts)
{
htmlContent += $@"
<tr>
<td>{forecast.Date.ToShortDateString()}</td>
<td>{forecast.TemperatureC}</td>
<td>{forecast.Summary}</td>
</tr>";
}
htmlContent += @"
</table>
</body>
</html>";
// Convert the HTML string to a PDF using IronPDF
var renderer = new ChromePdfRenderer();
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
// Retrieve the byte array of the generated PDF
var pdfBytes = pdfDocument.BinaryData;
// Return the PDF file to the client
return File(pdfBytes, "application/pdf", "WeatherForecast.pdf");
}
}
}
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf
Namespace WebApplication8.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
<HttpGet(Name := "GetWeatherForecast")>
Public Function GetWeatherForecastPdf() As IActionResult
Dim htmlContent = "
<html>
<head>
<title>Weather Forecast</title>
</head>
<body>
<h1>Weather Forecast</h1>
<table>
<tr>
<th>Date</th>
<th>Temperature (Celsius)</th>
<th>Summary</th>
</tr>"
Dim forecasts = 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))
})
' Iterate over the forecasts and add data to the HTML string
For Each forecast In forecasts
htmlContent &= $"
<tr>
<td>{forecast.Date.ToShortDateString()}</td>
<td>{forecast.TemperatureC}</td>
<td>{forecast.Summary}</td>
</tr>"
Next forecast
htmlContent &= "
</table>
</body>
</html>"
' Convert the HTML string to a PDF using IronPDF
Dim renderer = New ChromePdfRenderer()
Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Retrieve the byte array of the generated PDF
Dim pdfBytes = pdfDocument.BinaryData
' Return the PDF file to the client
Return File(pdfBytes, "application/pdf", "WeatherForecast.pdf")
End Function
End Class
End Namespace

下載並打開附加的PDF文件。

結論
OpenAPI,以前稱為Swagger,在.NET生態系統中通過Swashbuckle等庫簡化了RESTful API的設計和文件,促進了自動API文件生成,適用於ASP.NET Core項目。 展示OpenAPI和IronPDF之間的協同效應,我們展示了如何利用IronPDF的功能生成HTML內容的PDF文件並將其作為API回應返回,提升ASP.NET應用程式的功能。 通過採納OpenAPI標準並利用IronPDF的強大功能,開發人員可以增強其API文件實踐,向使用者提供完善、功能豐富的應用程式。
有關IronPDF授權的詳細資訊,請參閱IronPDF授權詳細資訊。 此外,您可以探索我們的HTML轉PDF轉換教程以獲取更多指導。
常見問題
如何在ASP.NET應用程式中將HTML內容轉換為PDF?
您可以在ASP.NET應用程式中使用IronPDF將HTML內容轉換為PDF。通過利用IronPDF的功能,您可以將HTML字串或文件渲染為PDF文件,然後可以作為API回應提供或保存以進行文件管理。
OpenAPI在.NET生態系統中扮演了什麼角色?
OpenAPI在.NET生態系統中扮演了至關重要的角色,它提供了一種標準化的方式來定義和記錄RESTful API。這種整合通常通過像Swashbuckle這樣的工具促進,這有助於生成OpenAPI規範,並在ASP.NET Core專案中便於API的使用。
如何使用Swashbuckle在.NET專案中設置Swagger UI?
要使用Swashbuckle在.NET專案中設置Swagger UI,請通過NuGet安裝Swashbuckle.AspNetCore套件。然後,在您的Program.cs文件中配置Swagger服務,並設置Swagger中介軟體以啟用透過Swagger UI自動生成和存取API文件。
如何在.NET中從OpenAPI定義生成客戶端SDK?
OpenAPI定義可以用來生成客戶端SDK,通過抽象API呼叫的複雜性來促進API的使用。在.NET中,像Swashbuckle這樣的工具可以生成這些定義,然後可以使用像AutoRest這樣的工具來使用各種編程語言建立客戶端SDK。
在OpenAPI文件中使用自定義註解有哪些優勢?
在OpenAPI文件中使用自定義註解可以增強API規範的清晰度和詳細度。在.NET中,Swashbuckle允許您使用SwaggerOperation和SwaggerResponse等屬性來新增描述和響應程式碼,使API文件更加資訊豐富且便於開發者理解。
如何在ASP.NET Core中將PDF文件作為API回應提供?
您可以在ASP.NET Core中使用IronPDF將PDF文件作為API回應提供。使用IronPDF的渲染方法從HTML內容生成PDF,然後在您的API控制器操作中使用ASP.NET Core的IActionResult將文件作為回應的一部分輸出。
在ASP.NET應用程式中結合OpenAPI和PDF生成工具有何益處?
在ASP.NET應用程式中結合OpenAPI和像IronPDF這樣的PDF生成工具提供了全面的API文件,並通過允許API返回專業的PDF文件來增強功能。這種整合支持高效的文件管理並豐富了應用程式的整體能力。




