跳過到頁腳內容
.NET幫助

Ocelot .NET(對於開發者的運行原理)

Ocelot API Gateway 是一個 .NET 庫,它實現了 API 閘道器模式,通常用於 API 閘道器,以處理多個微服務之間的請求。 它作為輕量級的 API 閘道器,將客戶端的請求路由到下游服務。 這篇文章深入探討了 Ocelot API 閘道器如何介於客戶端和下游服務之間,涵蓋其安裝、配置、主要功能和實際示例,以展示其功能。 我們還將探索 IronPDF 概覽 和 Ocelot API 的結合。

什麼是 Ocelot .NET?

Ocelot .NET(開發人員的工作原理):圖1 - Ocelot .NET 主頁

Ocelot 是一個開源的 API 閘道器解決方案,適用於 .NET 應用程式,設計來促進多個微服務之間的路由請求。 它作為反向代理,管理來自客戶端的 HTTP 請求,並將它們路由到 ASP.NET Core 環境中的相應服務。 基於 ASP.NET Core 開發,Ocelot 與 .NET 生態系統無縫整合,提供對現代應用至關重要的一套強大功能。

Ocelot 的主要功能

路由

Ocelot 的功能核心是其路由能力。 它根據開發人員指定的配置,將來自客戶端的請求匹配到相應的服務路由,並可以與服務發現機制整合。 這包括對通配符路由的支持,這在處理不同 API 版本或眾多服務端點時特別有用。

中介層 / 委託處理程序

Ocelot 允許開發人員注入自定義中介層或處理程序,這可以在請求和響應到達客戶端或服務之前處理它們。這對於添加標頭、記錄請求或根據需要修改響應結構非常有用。

負載均衡

Ocelot 支持多種負載均衡策略,例如輪詢、最小連接和自訂提供者,若預定義策略都不適合需求。 此功能確保負載在可用服務之間均勻分配,增強了應用程式的整體彈性和效率。

身份驗證和授權

保護 API 端點至關重要,而 Ocelot 提供了與現有身份驗證提供者(如 Identity Server)整合的支持。 它支持流行的身份驗證方案,包括 JWT 和 OAuth2,允許對用戶訪問服務進行細粒度控制。

速率限制和質量保證

速率限制對於防止濫用和確保服務的公平使用至關重要,限製用戶在給定時間內可以發出的請求數量。 服務質量(QoS)選項如設置超時和重試,確保服務在各種網路條件和負載下保持可用和響應。

在 .NET 專案中設置 Ocelot

要將 Ocelot 整合到您的專案中,您需要通過 NuGet 安裝 Ocelot 套件,並在 Program 類中配置它:

dotnet add package Ocelot

Ocelot .NET(開發人員的工作原理):圖2 - 通過 NuGet 套件管理器安裝 Ocelot .NET

在您的 Startup.csProgram.cs 類中配置包括了請求構建器中介層的服務,以設置服務容器:

public void ConfigureServices(IServiceCollection services)
{
    // Add Ocelot services to the service collection
    services.AddOcelot();
}

public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Use the developer exception page when in development mode
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Start Ocelot middleware
    await app.UseOcelot();
}
public void ConfigureServices(IServiceCollection services)
{
    // Add Ocelot services to the service collection
    services.AddOcelot();
}

public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Use the developer exception page when in development mode
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Start Ocelot middleware
    await app.UseOcelot();
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Add Ocelot services to the service collection
	services.AddOcelot()
End Sub

Public Async Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
	' Use the developer exception page when in development mode
	If env.IsDevelopment() Then
		app.UseDeveloperExceptionPage()
	End If

	' Start Ocelot middleware
	Await app.UseOcelot()
End Sub
$vbLabelText   $csharpLabel

在 Ocelot 中配置路線

Ocelot 使用一個配置文件,通常是 ocelot.json,來定義路由規則。 這是一個更複雜的示例,演示了多路線的配置:

{
    "ReRoutes": [
        {
            "DownstreamPathTemplate": "/api/users/{id}",
            "DownstreamScheme": "https",
            "DownstreamHostAndPorts": [
                {
                    "Host": "userapi.com",
                    "Port": 443
                }
            ],
            "UpstreamPathTemplate": "/users/{id}",
            "UpstreamHttpMethod": ["Get"]
        },
        {
            "DownstreamPathTemplate": "/api/products/{id}",
            "DownstreamScheme": "https",
            "DownstreamHostAndPorts": [
                {
                    "Host": "productapi.com",
                    "Port": 443
                }
            ],
            "UpstreamPathTemplate": "/products/{id}",
            "UpstreamHttpMethod": ["Get"]
        }
    ],
    "GlobalConfiguration": {
        "BaseUrl": "http://yourgateway.com"
    }
}

此配置指定 API 閘道器如何根據路徑和 HTTP 方法,使用 JSON 文件設定將請求路由到不同的下游服務。

在 Ocelot .NET 中使用 IronPDF

Ocelot .NET(開發人員的工作原理):圖3 - IronPDF 首頁

在 .NET 應用程式中將 Ocelot 與 IronPDF 的 HTML 到 PDF 轉換 結合,提供了一個強大的解決方案,可以將生成 PDF 的請求路由到特定服務或在內部處理它們。 在這裡,我將指導您設置一個基本的 .NET Core 應用程式,使用 Ocelot 作為 API 閘道器,並使用 IronPDF 將 HTML 生成 PDF。

IronPDF 在HTML 到 PDF轉換方麵表現出色,確保準確保持原始佈局和樣式。 它非常適合從網路內容生成 PDF,如報告、發票和文檔。 支持 HTML 文件、URL 和原始 HTML 字串的 IronPDF 可以輕鬆生成高質量的 PDF 文檔。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Convert HTML string to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // Convert HTML file to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Convert HTML string to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // Convert HTML file to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' Convert HTML string to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' Convert HTML file to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

步驟 1:設置 .NET Core 網頁應用程式

首先,創建一個新的 .NET Core Web API 項目。 您可以使用 .NET CLI 或 Visual Studio 來完成。

使用 .NET CLI:

dotnet new webapi -n OcelotWithIronPDF
cd OcelotWithIronPDF
dotnet new webapi -n OcelotWithIronPDF
cd OcelotWithIronPDF
SHELL

步驟 2:添加必要的套件

您需要安裝 Ocelot 和 IronPDF。 您可以通過 NuGet 添加這些套件。

dotnet add package Ocelot
dotnet add package IronPdf
dotnet add package Ocelot
dotnet add package IronPdf
SHELL

步驟 3:配置 Ocelot

在專案的根目錄中添加一個 ocelot.json 文件,內容如下,用於配置 Ocelot 的路由。 此設置假設您希望 Ocelot 將 PDF 生成請求路由到將由應用程式內的 IronPDF 處理的特定路徑。

{
    "ReRoutes": [
        {
            "DownstreamPathTemplate": "/api/pdf",
            "DownstreamScheme": "https",
            "DownstreamHostAndPorts": [
                {
                    "Host": "localhost",
                    "Port": 5001
                }
            ],
            "UpstreamPathTemplate": "/generatepdf",
            "UpstreamHttpMethod": ["Post"]
        }
    ],
    "GlobalConfiguration": {
        "BaseUrl": "http://localhost:5000"
    }
}

步驟 4:配置 Startup.cs

更新 Startup.cs 以包括 Ocelot 的中介層。 確保您還配置了應用程式以使用靜態文件,因為 IronPDF 可能需要從本地文件系統加載資源。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddOcelot();
    }

    public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        await app.UseOcelot();
    }
}
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddOcelot();
    }

    public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        await app.UseOcelot();
    }
}
Public Class Startup
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		services.AddControllers()
		services.AddOcelot()
	End Sub

	Public Async Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
		If env.IsDevelopment() Then
			app.UseDeveloperExceptionPage()
		End If

		app.UseRouting()
		app.UseAuthorization()

		app.UseEndpoints(Sub(endpoints)
			endpoints.MapControllers()
		End Sub)

		Await app.UseOcelot()
	End Sub
End Class
$vbLabelText   $csharpLabel

步驟 5:使用 IronPDF 實現 PDF 生成

在 Controllers 文件夾中新建一個控制器 PdfController.cs 。 此控制器將處理 PDF 生成請求。

using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace OcelotWithIronPDF.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PdfController : ControllerBase
    {
        [HttpPost]
        public IActionResult CreatePdfFromHtml([FromBody] string htmlContent)
        {
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);
            var output = pdf.BinaryData;

            // Return the PDF as a file result
            return File(output, "application/pdf", "generated.pdf");
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace OcelotWithIronPDF.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PdfController : ControllerBase
    {
        [HttpPost]
        public IActionResult CreatePdfFromHtml([FromBody] string htmlContent)
        {
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);
            var output = pdf.BinaryData;

            // Return the PDF as a file result
            return File(output, "application/pdf", "generated.pdf");
        }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf

Namespace OcelotWithIronPDF.Controllers
	<ApiController>
	<Route("api/[controller]")>
	Public Class PdfController
		Inherits ControllerBase

		<HttpPost>
		Public Function CreatePdfFromHtml(<FromBody> ByVal htmlContent As String) As IActionResult
			Dim renderer = New ChromePdfRenderer()
			Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
			Dim output = pdf.BinaryData

			' Return the PDF as a file result
			Return File(output, "application/pdf", "generated.pdf")
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

步驟 6:運行應用程式

確保您的應用程式正確配置,能在 ocelot.json 中指定的端口上監聽。 您可以在 Properties/launchSettings.json 中設置此項。

{
  "profiles": {
    "OcelotWithIronPDF": {
      "commandName": "Project",
      "launchBrowser": false,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

現在,運行您的應用程式,您應該可以將 HTML 內容發送到 http://localhost:5000/generatepdf 並接收一個 PDF 作為響應。

Ocelot .NET(開發人員的工作原理):圖4

此示例展示了在同一應用程式中使用 Ocelot 和 IronPDF 的基本實施。 對於生產場景,考慮保護您的端點,處理錯誤場景,並根據具體需求優化 PDF 生成過程。

結論

Ocelot .NET(開發人員的工作原理):圖5 - IronPDF 授權頁面

總之,Ocelot 是一個卓越的選擇,用於在微服務架構中管理和路由請求。 其強大的功能如路由、負載均衡、中介層支持和身份驗證,對於任何 .NET 開發人員來說都是一個強大的工具。 通過遵循提供的詳細步驟,您可以有效地將 Ocelot 整合到您的 .NET 專案中,以簡化您的 API 閘道器需求。

此外,如果您需要 PDF 生成功能,結合 Ocelot 和 IronPDF 非常簡單,並可以增強您的應用程式的功能。 IronPDF 提供 免費試用,而許可證則是一個經濟實惠的解決方案。

通過結合 Ocelot 和 IronPDF,您可以建構一個全面且高效的微服務基礎架構,滿足路由和文件生成的需求。

常見問題解答

Ocelot 如何改善 .NET 應用程序中的微服務通信?

Ocelot 作為 API 網關,促進在 .NET 應用程序中多個微服務之間的高效路由和管理 HTTP 請求。它提供路由、負載平衡和身份驗證等功能,以簡化服務之間的通信。

使用 Ocelot 與 IronPDF 有何好處?

將 Ocelot 與 IronPDF 整合,使開發者能夠在 .NET 應用程序中高效地路由 PDF 生成請求。IronPDF 確保 HTML 到 PDF 的轉換保持原始佈局和樣式,使其成為生成基於網頁的內容(如報告和發票)的理想選擇。

如何配置 Ocelot 的負載平衡?

Ocelot 支持多種負載平衡策略,包括輪詢法和最小連接數法,可以通過通常命名為 ocelot.json 的 JSON 文件進行配置。這確保了對微服務的均勻流量分配。

中介軟體在 Ocelot 的架構中扮演什麼角色?

在 Ocelot 中,中介軟體允許開發者插入自定義處理程序來處理請求和響應。這對於添加標頭、記錄或修改響應等任務非常有用,增強了 API 網關的靈活性和功能。

如何在 .NET 項目中設置 Ocelot?

要在 .NET 項目中設置 Ocelot,請通過 NuGet 安裝 Ocelot 包,然後通過在 Program 類中添加 Ocelot 服務並在配置文件中定義路由來進行配置。此設置有助於路由和管理 API 請求。

Ocelot 使用哪些策略來處理路由?

Ocelot 使用 ocelot.json 文件中指定的配置驅動路由,將請求從 API 網關引導到適當的下游服務。它支持通配符路由和服務發現機制,提供靈活的路由設置。

Ocelot 如何確保 API 的安全訪問?

Ocelot 與 Identity Server 等身份驗證提供程序集成,並支持 JWT 和 OAuth2 協議,通過控制用戶權限並確保端點保護來實現安全的 API 訪問。

Ocelot 可以用來優化 PDF 生成工作流程嗎?

可以,Ocelot 可以將請求路由到專門用於 PDF 生成的服務,如使用 IronPDF 的服務。這樣的設置通過高效處理請求並在轉換過程中保留文檔的完整性來優化 PDF 工作流程。

Ocelot 如何與服務發現機制集成?

Ocelot 支持與 Consul 和 Eureka 等服務發現機制的集成,這允許它根據服務的當前狀態動態路由請求。這種集成簡化了微服務架構中的服務管理。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。