
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
首先,您需要通过NuGet在Visual Studio中安装Swashbuckle.AspNetCore包。 您可以使用NuGet包管理器控制台来完成此操作:
或者使用.NET CLI:
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();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();
}
}
}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生成集成到他们的Web项目中,为用户提供增强的文档管理能力。 无论是从头开始创建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");
}
}
}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,通过Swashbuckle等库在.NET生态系统中简化了RESTful API的设计和文档编制,便于为ASP.NET Core项目自动生成API文档。 展示OpenAPI与IronPDF之间的协同作用,我们展示了如何利用IronPDF的功能从HTML内容生成PDF文件并将其作为API响应返回,丰富了ASP.NET应用程序的功能。 通过采用OpenAPI标准并利用IronPDF的强大功能,开发者可以增强其API文档实践并为用户提供完善的、功能丰富的应用程序。
有关IronPDF许可的详细信息,请参阅IronPDF许可详情。 另外,您可以浏览我们的HTML到PDF转换教程以获得更多指导。

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。
相关文章


