?? API Gateway in Microservices – .NET 9 with C#

?? API Gateway in Microservices – .NET 9 with C#

?? What is an API Gateway?

An API Gateway is a single entry point for all client requests in a Microservices architecture. Instead of clients calling multiple services directly, they send requests to the API Gateway, which then routes them to the appropriate microservices.

? Why use an API Gateway?

  • ?? Simplifies client communication by exposing a single URL
  • ?? Enhances security by handling authentication & authorization centrally
  • ? Improves performance with caching, rate-limiting, and load balancing
  • ?? Routes requests dynamically to the right microservice
  • ?? Reduces client complexity by aggregating multiple responses into one


Building an API Gateway in .NET 9 using Ocelot

?? Step 1: Create a New API Gateway Project

Open Visual Studio and create an ASP.NET Core Web API project targeting .NET 9.

?? Install Ocelot (Make sure you're using the latest version compatible with .NET 9) in API Gateway project:

Install-Package Ocelot

?? Step 2: Configure Ocelot in ocelot.json

Create a new file ocelot.json in the root of your project and define routes for microservices.

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/products",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        { "Host": "localhost", "Port": 5001 }
      ],
      "UpstreamPathTemplate": "/api/products",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/orders",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        { "Host": "localhost", "Port": 5002 }
      ],
      "UpstreamPathTemplate": "/api/orders",
      "UpstreamHttpMethod": [ "GET" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:5000"
  }
}        

?? Explanation:

  • /api/products → Routes to Product Service running on localhost:5001
  • /api/orders → Routes to Order Service running on localhost:5002


?? Step 3: Register Ocelot in Program.cs

Modify Program.cs to configure Ocelot Middleware in .NET 9:

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

// Add Ocelot configuration
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot();

var app = builder.Build();

// Use Ocelot Middleware
await app.UseOcelot();

app.Run();        

?? What’s happening here?

  • ?? Loads ocelot.json configuration
  • ? Registers Ocelot services
  • ?? Enables Ocelot middleware to handle routing


?? Step 4: Create Microservices (Product & Order Services)

? Product Service (ProductService running on port 5001)

Create a new ASP.NET Core Web API project for the Product Service, update appsettings.json:

{
  "Urls": "https://localhost:5001"
}        

Modify Program.cs to return some sample data:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", () => new[] { "Laptop", "Phone", "Tablet" });

app.Run();        

? Order Service (OrderService running on port 5002)

Create another Web API project for Order Service, update appsettings.json:

{
  "Urls": "https://localhost:5002"
}        

Modify Program.cs to return sample data:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/orders", () => new[] { "Order1", "Order2", "Order3" });

app.Run();        

?? Step 5: Run & Test the API Gateway

Run all three projects:

1?? API Gateway (localhost:5000)

2?? Product Service (localhost:5001)

3?? Order Service (localhost:5002)

Now, test the API Gateway:

?? Call Product API via Gateway

GET https://localhost:5000/api/products

Response:

["Laptop", "Phone", "Tablet"]

?? Key Takeaways

? API Gateway acts as a single entry point for clients.

? Routes requests to the correct microservice behind the scenes.

? Enhances security, load balancing, and performance.

? Reduces direct exposure of microservices to clients.

?? With this setup, your microservices communicate efficiently using .NET 9 & Ocelot!

#DotNet #CSharp #Microservices #APIGateway #Ocelot #SoftwareDevelopment #CloudComputing #DevOps #BackendDevelopment #CodeWithCSharp

要查看或添加评论,请登录

Paresh Bhayani的更多文章

社区洞察