.NET 幫助

OpenAPI .NET(適用於開發人員的工作原理)

發佈 2024年7月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 文檔。 您可以通過導航至此來查看這些 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#

在這個例子中,SwaggerOperationSwaggerResponse 屬性被用來為端點提供詳細的 OpenAPI 描述和響應代碼。

輸出

OpenAPI .NET(對開發者的運作方式):圖 1 - 自訂註解輸出

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

OpenAPI .NET(開發人員的工作方式):圖 2 - 回應輸出

IronPDF

IronPDF for ASP.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 呼叫。

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 - API 輸出

下載並開啟附加的 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,622,374 查看許可證 >