跳過到頁腳內容
.NET幫助

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

Ocelot API Gateway是一個.NET函式庫,它實作了 API 閘道模式,這種模式通常用於 API 閘道中,以處理跨多個微服務的請求。 它充當輕量級 API 網關,將客戶端的請求路由到下游服務。 本文深入探討了 Ocelot API 閘道在客戶端和下游服務之間的作用,涵蓋了其安裝、配置、主要特性以及演示其功能的實際範例。 我們也將探討IronPDF概述和 Ocelot API 的結合應用。

什麼是 Ocelot .NET?

Ocelot .NET (開發者使用指南):圖 1 - Ocelot .NET首頁

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

Ocelot 的主要特點

路由

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

中介軟體/委託處理程序

Ocelot 允許開發者註入自訂中間件或處理程序,以便在請求和回應到達用戶端或服務之前進行處理。這對於新增請求頭、記錄請求日誌,甚至根據需要修改回應結構都非常有用。

負載平衡

Ocelot 開箱即用支援多種負載平衡策略,例如輪詢、最少連線數,如果預先定義的策略都不符合要求,也可以使用自訂提供者。 此功能可確保負載均勻分佈在可用服務之間,從而提高應用程式的整體彈性和效率。

身份驗證和授權

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

速率限制和QoS

速率限制對於防止濫用和確保服務的公平使用至關重要,它限制使用者在給定時間內可以發出的請求次數。 服務品質 (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();
}
$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 (開發者使用方法):圖 3 - IronPDF主頁

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

IronPDF在HTML 轉 PDF 方面表現出色,可確保精確保留原始佈局和樣式。 它非常適合從基於 Web 的內容(例如報告、發票和文件)建立 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

步驟二:新增必要的軟體包

您需要安裝 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"
      }
    }
  }
}

現在,運行你的應用程序,你應該能夠向 http://localhost:5000/generatepdf 發送 HTML 內容,並收到 PDF 作為回應。

Ocelot .NET (開發者使用方法):圖 4

本範例展示了在同一個應用程式中使用IronPDF實現 Ocelot 的基本方法。 對於生產環境,請考慮保護您的端點安全、處理錯誤情況,並根據您的特定要求最佳化 PDF 生成流程。

結論

Ocelot .NET (開發者使用方法):圖 5 - IronPDF許可頁面

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

此外,如果您需要 PDF 生成功能,將IronPDF與 Ocelot 整合非常簡單,並且可以增強應用程式的功能。 IronPDF提供免費試用版,許可證價格從經濟實惠的價格起,是滿足您 PDF 需求的理想解決方案。

透過結合 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 等服務發現機制的集成,這允許它根據服務的當前狀態動態路由請求。這種集成簡化了微服務架構中的服務管理。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me