푸터 콘텐츠로 바로가기
.NET 도움말

Ocelot .NET (How It Works For Developers)

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();
}
$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");
    }
}
$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();
    }
}
$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");
        }
    }
}
$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.

자주 묻는 질문

Ocelot은 .NET 애플리케이션에서 마이크로서비스 커뮤니케이션을 어떻게 개선할 수 있나요?

Ocelot은 API 게이트웨이 역할을 수행하여 .NET 애플리케이션의 여러 마이크로서비스에서 HTTP 요청을 효율적으로 라우팅하고 관리할 수 있도록 지원합니다. 라우팅, 부하 분산, 인증과 같은 기능을 제공하여 서비스 간의 통신을 간소화합니다.

IronPDF와 함께 Ocelot을 사용하면 어떤 이점이 있나요?

Ocelot과 IronPDF를 통합하면 개발자가 .NET 애플리케이션 내에서 PDF 생성 요청을 효율적으로 라우팅할 수 있습니다. IronPDF는 HTML을 PDF로 변환할 때 원본 레이아웃과 스타일을 유지하므로 보고서 및 송장과 같은 웹 기반 콘텐츠를 생성하는 데 이상적입니다.

로드 밸런싱을 위해 Ocelot을 어떻게 구성하나요?

Ocelot은 라운드 로빈 및 최소 연결 등 다양한 로드 밸런싱 전략을 지원하며, 이는 일반적으로 ocelot.json이라는 JSON 파일을 통해 구성할 수 있습니다. 이를 통해 마이크로서비스 전반에 걸쳐 트래픽을 고르게 분산할 수 있습니다.

미들웨어는 오셀롯의 아키텍처에서 어떤 역할을 하나요?

Ocelot의 미들웨어를 사용하면 개발자가 사용자 지정 핸들러를 삽입하여 요청과 응답을 처리할 수 있습니다. 이는 헤더 추가, 로깅 또는 응답 수정과 같은 작업에 유용하며 API 게이트웨이의 유연성과 기능을 향상시킵니다.

.NET 프로젝트에서 Ocelot을 어떻게 설정할 수 있나요?

.NET 프로젝트에서 Ocelot을 설정하려면 NuGet을 통해 Ocelot 패키지를 설치한 다음, Program 클래스에서 Ocelot 서비스를 추가하고 구성 파일에서 경로를 정의하여 구성합니다. 이 설정은 API 요청의 라우팅 및 관리를 용이하게 합니다.

오셀롯은 라우팅을 처리하기 위해 어떤 전략을 사용하나요?

Ocelot은 ocelot.json 파일에 지정된 구성 중심 라우팅을 사용하여 API 게이트웨이의 요청을 적절한 다운스트림 서비스로 전달합니다. 유연한 라우팅 설정을 위해 와일드카드 라우팅 및 서비스 검색 메커니즘을 지원합니다.

오셀롯은 어떻게 안전한 API 액세스를 보장하나요?

Ocelot은 Identity Server와 같은 인증 제공업체와 통합되며 JWT 및 OAuth2 체계를 지원하여 사용자 권한을 제어하고 엔드포인트 보호를 보장함으로써 안전한 API 액세스를 가능하게 합니다.

PDF 생성 워크플로우를 최적화하는 데 Ocelot을 사용할 수 있나요?

예, Ocelot은 요청을 IronPDF를 사용하는 것과 같은 PDF 생성 전용 서비스로 라우팅할 수 있습니다. 이 설정은 요청을 효율적으로 처리하고 변환 중에 문서 충실도를 유지하여 PDF 워크플로우를 최적화합니다.

Ocelot은 서비스 검색 메커니즘과 어떻게 통합되나요?

Ocelot은 현재 서비스 상태에 따라 요청을 동적으로 라우팅할 수 있는 Consul 및 Eureka와 같은 서비스 검색 메커니즘과의 통합을 지원합니다. 이러한 통합은 마이크로서비스 아키텍처에서 서비스 관리를 간소화합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.