跳過到頁腳內容
.NET HELP

Ocelot .NET (How It Works For Developers)

Ocelot API Gateway 是一個 .NET 函式庫,可實作 API 閘道常用的 API 閘道模式,以處理跨越多個微服務的請求。 它扮演輕量級 API 閘道的角色,將客戶端的要求路由至下游服務。 本文將深入介紹 Ocelot API 閘道如何位於用戶端與下游服務之間,涵蓋其安裝、組態、主要功能,以及展示其功能的實用範例。 我們也將探討 IronPDF 總覽與 Ocelot API 的結合。

什麼是 Ocelot .NET?

Ocelot .NET (How It Works For Developers):圖 1 - Ocelot .NET 首頁

Ocelot 是適用於 .NET 應用程式的開放原始碼 API 閘道解決方案,其設計目的在於促進多個微服務之間的請求路由。 它扮演反向代理的角色,管理來自用戶端的 HTTP 請求,並將它們路由到 ASP.NET Core 環境中的適當服務。 Ocelot 基於 ASP.NET Core 開發,可與 .NET 生態系統無縫整合,提供對現代應用程式至關重要的強大功能。

Ocelot 的主要功能

路由

Ocelot 功能的核心是其路由功能。 它可根據開發人員指定的組態,將傳入的請求配對至適當的服務路徑,並可與服務發現機制整合。 這包括支援通配符路由,這在處理不同 API 版本或眾多服務端點時特別有用。

中介軟體/委託處理程式

Ocelot 可讓開發人員注入自訂的中介軟體或處理程式,這些中介軟體或處理程式可在請求與回應抵達用戶端或服務之前進行處理。這對於新增標頭、記錄請求,甚至根據需要修改回應結構都很有用。

負載平衡

Ocelot 支援多種開箱即用的負載平衡策略,例如 Round Robin、Least Connection,如果預定義的策略都不符合需求,還可使用自訂的提供者。 此功能可確保負載在可用的服務間平均分配,提升應用程式的整體彈性與效率。

驗證與授權

確保 API 端點的安全至關重要,Ocelot 提供與現有驗證供應商 (例如 Identity Server) 整合的支援。 它支援流行的驗證方案,包括 JWT 和 OAuth2,並允許對使用者存取服務進行精細控制。

速率限制和 QoS

費率限制對於防止濫用和確保公平使用服務是非常重要的,它可以限制使用者在指定時間內的請求數量。 服務品質 (QoS) 選項,例如設定逾時和重試,可確保服務在各種網路條件和負載下都能保持可用且反應迅速。

在 .NET 專案中設定 Ocelot

要將 Ocelot 整合到您的專案中,您需要透過 NuGet 安裝 Ocelot 套件,並在 Program class 中進行設定:

dotnet add package Ocelot

Ocelot .NET (How It Works For Developers):圖 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();
}
$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"
    }
}

此設定會根據路徑和 HTTP 方法,指定如何將向 API 閘道提出的要求路由至不同的下游服務,並使用 JSON 檔案進行設定。

使用 IronPDF 與 Ocelot .NET

Ocelot .NET (How It Works For Developers):圖 3 - IronPDF 首頁

在 .NET 應用程式中將 Ocelot 與 IronPDF 的 HTML-to-PDF 轉換結合,可提供功能強大的解決方案,您可以將 PDF 生成請求路由至特定服務或在內部處理。 在此,我將引導您建立一個基本的 .NET Core 應用程式,該程式使用 Ocelot 作為 API Gateway,並使用 IronPDF 從 HTML 生成 PDF。

IronPDF 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,可輕鬆製作高品質的 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");
    }
}
$vbLabelText   $csharpLabel

步驟 1:設定 .NET Core Web 應用程式

首先,建立一個新的 .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();
    }
}
$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");
        }
    }
}
$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 (How It Works For Developers):圖 4

本範例展示了 Ocelot 與 IronPDF 在同一應用程式中的基本實作。 針對生產情境,請考慮保護您的端點、處理錯誤情境,並根據您的特定需求優化 PDF 生成流程。

結論

Ocelot .NET (How It Works For Developers):圖 5 - IronPDF 授權頁面

總而言之,Ocelot 是微服務架構中管理和路由請求的絕佳選擇。 其強大的功能,如路由、負載平衡、中介軟體支援及驗證,使其成為任何 .NET 開發人員的強大工具。 按照提供的詳細步驟,您可以有效地將 Ocleot 整合到您的 .NET 專案中,以簡化您的 API Gateway 需求。

此外,如果您需要 PDF 生成功能,將 IronPDF 與 Ocelot 整合會非常直接,並可增強應用程式的功能。 IronPdf 提供 免費試用,授權起始價格經濟實惠,滿足您的 PDF 需求。

透過同時利用 Ocelot 和 IronPDF,您可以建立一個全面且有效率的微服務基礎架構,同時滿足路由和文件產生的需求。

常見問題解答

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

Ocelot 可作為 API 閘道,促進 .NET 應用程式中多個微服務之間 HTTP 請求的有效路由和管理。它提供路由、負載平衡和驗證等功能,以簡化服務間的通訊。

使用 Ocelot 與 IronPDF 有什麼好處?

將 Ocelot 與 IronPDF 整合,可讓開發人員在 .NET 應用程式中有效地路由 PDF 生成請求。IronPDF 可確保 HTML 到 PDF 的轉換能維持原始的版面與樣式,因此非常適合產生基於網頁的內容,例如報表和發票。

如何配置 Ocelot 進行負載平衡?

Ocelot 支援多種負載平衡策略,包括 Round Robin 和 Least Connection,可透過一般名為 ocelot.json 的 JSON 檔案進行設定。這可確保流量在微服務間平均分配。

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

Ocelot 中的中介軟體允許開發人員插入自訂處理程式來處理請求與回應。這對於新增標頭、日誌或修改回應等工作非常有用,可增強 API 閘道的彈性和功能。

如何在 .NET 專案中設定 Ocelot?

要在 .NET 專案中設定 Ocelot,先透過 NuGet 安裝 Ocelot 套件,然後透過在 Program class 中新增 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 等服務發現機制的整合,可根據服務的目前狀態動態路由請求。這種整合簡化了微服務架構中的服務管理。

Jacob Mellor,技術長 @ Team Iron
首席技術長

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。