跳過到頁腳內容
.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();
}
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"
    }
}

此設定會根據路徑和 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");
    }
}
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 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();
    }
}
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> 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"
      }
    }
  }
}

現在,執行您的應用程式,您應該能夠向 http://localhost:5000/generatepdf 發送 HTML 內容,並收到 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 支持多種負載平衡策略,包括輪詢法和最小連接數法,可以通過通常命名為 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技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我