跳至頁尾內容
.NET 幫助

Ocelot .NET(開發者使用指南)

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 的轉換保持原始佈局和樣式,使其成為產生報告和發票等 Web 內容的理想選擇。

如何設定 Ocelot 進行負載平衡?

Ocelot 支援多種負載平衡策略,包括輪詢(Round Robin)和最少連接(Least Connection),這些策略可以透過通常名為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 等服務發現機制集成,從而能夠根據服務的當前狀態動態路由請求。這種整合簡化了微服務架構中服務的管理。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。