.NET 帮助

OpenAPI .NET(开发者如何使用)

发布 2024年七月1日
分享:

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

第 2 步:配置 Swashbuckle

接下来,您需要在 ASP.NET Core 项目中配置 Swashbuckle。 这涉及更新 Startup.cs 文件,以添加 Swagger 服务并配置 Swagger 中间件。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI description at https://aka.ms/aspnetcore/swashbuckle
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();
// Learn more about configuring Swagger/OpenAPI description at https://aka.ms/aspnetcore/swashbuckle
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()
' Learn more about configuring Swagger/OpenAPI description at https://aka.ms/aspnetcore/swashbuckle
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()
VB   C#

生成和查看 API 文档

一旦配置好 Swashbuckle,运行应用程序时就会自动生成 OpenAPI 文档。 您可以通过导航到Swagger UI 界面.

使用 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
VB   C#

在本例中,"SwaggerOperation "和 "SwaggerResponse "属性用于提供端点的详细 OpenAPI 描述和响应代码。

输出

OpenAPI .NET(如何为开发人员工作):图 1 - 自定义注释输出

点击执行按钮,您将得到以下回复。

OpenAPI .NET(如何为开发人员工作):图 2 - 响应输出

IronPDF

IronPDF for .NET 是一款功能强大的工具,可在 ASP.NET 应用程序中无缝生成和处理 PDF 文档。 凭借其直观的 API 和强大的功能,开发人员可以毫不费力地将 PDF 生成功能集成到他们的网络项目中,为用户提供增强的文档管理功能。 无论是从零开始创建 PDF,将 HTML 内容转换为 PDF,还是添加图像和文本等动态元素,IronPDF 都能简化流程,确保高效、专业地生成文档。

使用 NuGet 包管理器安装的步骤:

  1. 在 Visual Studio 中打开 ASP.NET 项目,并导航到 "工具 "菜单。

  2. 选择 "NuGet 包管理器",然后点击 "管理解决方案的 NuGet 包"。

  3. 在 "浏览 "选项卡中搜索 "IronPDF "并选择所需的版本。 点击 "安装 "将软件包添加到您的项目中。 IronPDF 及其附属程序将自动下载并集成,使您可以开始在 ASP.NET 应用程序中无缝利用其功能。

    OpenAPI .NET(如何为开发人员工作):图 3 - IronPDF

响应 API 调用获取 PDF 文件

将以下代码添加到您的控制器文件中,它使用 IronPdf 创建 PDF 文件并将 PDF 文件返回给 API Call。

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)]
            });

            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 HTML to PDF
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Return PDF file
            var pdfBytes = pdfDocument.BinaryData;
            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)]
            });

            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 HTML to PDF
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Return PDF file
            var pdfBytes = pdfDocument.BinaryData;
            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))
			})

			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 HTML to PDF
			Dim renderer = New ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

			' Return PDF file
			Dim pdfBytes = pdfDocument.BinaryData
			Return File(pdfBytes, "application/pdf", "WeatherForecast.pdf")
		End Function
	End Class
End Namespace
VB   C#

OpenAPI .NET(如何为开发人员工作):图 4 - 应用程序接口输出

下载并打开所附 PDF 文件。

OpenAPI .NET(如何为开发人员工作):图 5 - 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 教程如需进一步指导,请联系

< 前一页
Humanizer C#(它是如何为开发人员工作的)
下一步 >
Microsoft.Extensions.Caching.Memory 示例(包含 PDF)在 C#

准备开始了吗? 版本: 2024.12 刚刚发布

免费NuGet下载 总下载量: 11,781,565 查看许可证 >