.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(通常可通过 http://localhost:5000/swagger访问)查看这些 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
VB   C#

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

输出

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

单击 "执行 "按钮,您将收到以下回复。

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

IronPDF

IronPDF for ASP.NET是一款功能强大的工具,可在ASP.NET应用程序中无缝生成和处理PDF文档。凭借其直观的应用程序接口和强大的功能,开发人员可以毫不费力地将 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 调用。

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.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >