Zum Fußzeileninhalt springen
.NET HILFE

Ocelot .NET (Funktionsweise für Entwickler)

Ocelot API Gateway is a .NET library that implements the API gateway pattern commonly used in API gateways to handle requests across multiple microservices. It acts as a lightweight API gateway, routing requests from clients to downstream services. This article provides an in-depth look at how the Ocelot API gateway sits between clients and downstream services, covering its installation, configuration, key features, and practical examples to demonstrate its capabilities. We'll also explore IronPDF Overview and Ocelot API combined.

What is Ocelot .NET?

Ocelot .NET (How It Works For Developers): Figure 1 - Ocelot .NET homepage

Ocelot is an open-source API gateway solution for .NET applications, designed to facilitate the routing of requests across multiple microservices. It acts as a reverse proxy, managing HTTP requests from clients and routing them to the appropriate services in an ASP.NET Core environment. Developed on ASP.NET Core, Ocelot integrates seamlessly with the .NET ecosystem, offering a robust set of features that are crucial for modern applications.

Key Features of Ocelot

Routing

At the core of Ocelot's functionality is its routing capability. It matches incoming requests to the appropriate service routes based on the configuration specified by developers, and it can be integrated with service discovery mechanisms. This includes support for wildcard routing, which is particularly useful when dealing with varying API versions or numerous service endpoints.

Middleware / Delegating Handlers

Ocelot allows developers to inject custom middleware or handlers that can process requests and responses before they reach the client or the service. This is useful for adding headers, logging requests, or even modifying the response structure as needed.

Load Balancing

Ocelot supports a variety of load-balancing strategies out of the box, such as Round Robin, Least Connection, and a custom provider if none of the predefined strategies fit the requirement. This feature ensures that the load is distributed evenly among the available services, enhancing the overall resilience and efficiency of the application.

Authentication and Authorization

Securing API endpoints is critical, and Ocelot provides support for integrating with existing authentication providers, such as Identity Server. It supports popular authentication schemes, including JWT and OAuth2, and allows for fine-grained control over user access to services.

Rate Limiting and QoS

Rate limiting is essential to prevent abuse and ensure fair use of the services by limiting the number of requests a user can make in a given period. Quality of Service (QoS) options like setting timeouts and retries ensure that services remain available and responsive under various network conditions and loads.

Setting Up Ocelot in a .NET Project

To integrate Ocelot into your project, you need to install the Ocelot package via NuGet and configure it in the Program class:

dotnet add package Ocelot

Ocelot .NET (How It Works For Developers): Figure 2 - Install Ocelot .NET through NuGet Package Manager

Configure the services, including the request builder middleware, in your Startup.cs or Program.cs class to set up the service container:

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

Configuring Routes in Ocelot

Ocelot uses a configuration file, typically ocelot.json, to define the routing rules. Here is a more complex example that demonstrates multiple route configurations:

{
    "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"
    }
}

This configuration specifies how requests to the API gateway are routed to different downstream services based on the path and HTTP method, using the JSON file for setup.

Using IronPDF with Ocelot .NET

Ocelot .NET (How It Works For Developers): Figure 3 - IronPDF homepage

Combining Ocelot with IronPDF's HTML-to-PDF Conversion in a .NET application provides a powerful solution where you can route PDF generation requests to a specific service or handle them internally. Here, I'll guide you through setting up a basic .NET Core application that uses Ocelot as an API Gateway and IronPDF to generate PDFs from HTML.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

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

Step 1: Set Up the .NET Core Web Application

First, create a new .NET Core Web API project. You can do this using the .NET CLI or Visual Studio.

Using the .NET CLI:

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

Step 2: Add Necessary Packages

You need to install Ocelot and IronPDF. You can add these packages via NuGet.

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

Step 3: Configure Ocelot

Add an ocelot.json file to the root of your project with the following content to configure Ocelot’s routing. This setup assumes you want Ocelot to route PDF generation requests to a specific path that will be handled by IronPDF within the same application.

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

Step 4: Configure Startup.cs

Update Startup.cs to include Ocelot’s middleware. Ensure you also configure your application to use static files, as IronPDF may need to load assets from the local file system.

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

Step 5: Implement PDF Generation with IronPDF

Create a new controller PdfController.cs in your Controllers folder. This controller will handle the PDF generation requests.

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

Step 6: Run the Application

Make sure your application is correctly configured to listen on the ports specified in ocelot.json. You can set this in Properties/launchSettings.json.

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

Now, run your application, and you should be able to post HTML content to http://localhost:5000/generatepdf and receive a PDF in response.

Ocelot .NET (How It Works For Developers): Figure 4

This example showcases a basic implementation of Ocelot with IronPDF within the same application. For production scenarios, consider securing your endpoints, handling error scenarios, and optimizing the PDF generation process based on your specific requirements.

Conclusion

Ocelot .NET (How It Works For Developers): Figure 5 - IronPDF licensing page

In conclusion, Ocelot is an excellent choice for managing and routing requests in a microservices architecture. Its robust features like routing, load balancing, middleware support, and authentication make it a powerful tool for any .NET developer. By following the detailed steps provided, you can effectively integrate Ocleot into your .NET projects to streamline your API Gateway needs.

Additionally, if you require PDF generation capabilities, integrating IronPDF with Ocelot is straightforward and enhances your application's functionality. IronPDF offers a free trial and licenses start from a cost-effective solution for your PDF needs.

By leveraging Ocelot and IronPDF together, you can build a comprehensive and efficient microservices infrastructure that meets both routing and document generation requirements.

Häufig gestellte Fragen

Wie kann Ocelot die Kommunikation von Microservices in .NET-Anwendungen verbessern?

Ocelot fungiert als API-Gateway und ermöglicht effizientes Routing und Management von HTTP-Anfragen über mehrere Microservices in einer .NET-Anwendung. Es bietet Funktionen wie Routing, Lastverteilung und Authentifizierung, um die Kommunikation zwischen Diensten zu optimieren.

Was sind die Vorteile der Verwendung von Ocelot mit IronPDF?

Die Integration von Ocelot mit IronPDF ermöglicht Entwicklern, Anfragen zur PDF-Erstellung effizient innerhalb einer .NET-Anwendung zu routen. IronPDF gewährleistet, dass HTML-zu-PDF-Konvertierungen originale Layouts und Stile bewahren, was es ideal für die Erstellung webbasierter Inhalte wie Berichte und Rechnungen macht.

Wie konfiguriert man Ocelot für Load Balancing?

Ocelot unterstützt verschiedene Load-Balancing-Strategien, einschließlich Round Robin und Least Connection, die über eine JSON-Datei namens ocelot.json konfiguriert werden können. Dies gewährleistet eine gleichmäßige Verteilung des Datenverkehrs über Microservices.

Welche Rolle spielt Middleware in der Architektur von Ocelot?

Middleware in Ocelot ermöglicht es Entwicklern, benutzerdefinierte Handler einzufügen, um Anfragen und Antworten zu verarbeiten. Dies ist nützlich für Aufgaben wie das Hinzufügen von Headern, Logging oder das Ändern von Antworten, wodurch die Flexibilität und Funktionalität des API-Gateways erhöht wird.

Wie kann man Ocelot in einem .NET-Projekt einrichten?

Um Ocelot in einem .NET-Projekt einzurichten, installieren Sie das Ocelot-Paket über NuGet, konfigurieren Sie es dann, indem Sie Ocelot-Dienste in der Program-Klasse hinzufügen und Routen in einer Konfigurationsdatei definieren. Diese Einrichtung erleichtert das Routing und Management von API-Anfragen.

Welche Strategien verwendet Ocelot zum Handling von Routing?

Ocelot verwendet konfigurationsgesteuertes Routing, welches in einer ocelot.json-Datei angegeben ist, um Anfragen vom API-Gateway an geeignete Downstream-Dienste zu leiten. Es unterstützt Wildcard-Routing und Diensterkennungsmechanismen für flexible Routing-Setups.

Wie gewährleistet Ocelot sicheren API-Zugang?

Ocelot integriert sich mit Authentifizierungsanbietern wie Identity Server und unterstützt JWT- und OAuth2-Schemata, um einen sicheren API-Zugang durch die Steuerung von Benutzerberechtigungen und den Schutz von Endpunkten zu gewährleisten.

Kann Ocelot verwendet werden, um PDF-Erstellungs-Workflows zu optimieren?

Ja, Ocelot kann Anfragen an spezifische Dienste leiten, die der PDF-Erstellung gewidmet sind, wie z. B. solche, die IronPDF verwenden. Dieses Setup optimiert PDF-Workflows, indem es Anfragen effizient bearbeitet und die Dokumenttreue während der Konvertierung erhält.

Wie integriert sich Ocelot mit Diensterkennungsmechanismen?

Ocelot unterstützt die Integration mit Diensterkennungsmechanismen wie Consul und Eureka, was es ermöglicht, Anfragen basierend auf dem aktuellen Zustand der Dienste dynamisch zu leiten. Diese Integration vereinfacht das Management von Diensten in einer Microservices-Architektur.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen