API Gateway in .Net Microservice Architecture
In a microservice architecture, an API Gateway serves as a single entry point for all client requests. It acts as a reverse proxy, routing client requests to the appropriate microservice and handling various cross-cutting concerns such as authentication, logging, and rate limiting. This approach simplifies the client interaction by providing a unified interface to multiple services, making the architecture more manageable and scalable.
Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. Uncover more by visiting our https://dotnet-fullstack-dev.blogspot.com reach out for further information.
Why Use an API Gateway?
- Simplified Client Interaction: Clients interact with a single endpoint rather than multiple services.
- Decoupling: The gateway abstracts the complexities of service-to-service communication.
- Cross-Cutting Concerns: The gateway can handle authentication, logging, monitoring, and rate limiting.
- Load Balancing: Distributes incoming requests evenly across multiple instances of services.
- Security: Centralized enforcement of security policies.
How API Gateway Works
- Client Request: The client sends a request to the API Gateway.
- Routing: The gateway routes the request to the appropriate microservice.
- Aggregation: If needed, the gateway aggregates responses from multiple services.
- Response: The gateway sends the response back to the client.
Implementing an API Gateway in .NET
We’ll use Ocelot, a popular .NET API Gateway library, to implement our API Gateway. Ocelot is lightweight, fast, scalable, and can handle multiple downstream services.
Step-by-Step Guide
Step 1: Set Up the Project
Create a new ASP.NET Core project:
dotnet new web -n ApiGateway
cd ApiGateway
Install Ocelot NuGet package:
dotnet add package Ocelot
dotnet add package Microsoft.Extensions.Configuration.Json
Step 2: Configure Ocelot
Create an ocelot.json
configuration file:
{
"Routes": [
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/products",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/orders",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5002
}
],
"UpstreamPathTemplate": "/orders",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000"
}
}
Modify Program.cs
to use Ocelot:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("ocelot.json");
builder.Services.AddOcelot();
var app = builder.Build();
app.UseOcelot().Wait();
app.Run();
Step 3: Create Downstream Services
Product Service (ProductService
):
- Create a new ASP.NET Core Web API project named
ProductService
. - Implement a simple controller to handle product-related requests.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new List<string> { "Product1", "Product2" };
return Ok(products);
}
}
Order Service (OrderService
):
- Create a new ASP.NET Core Web API project named
OrderService
. - Implement a simple controller to handle order-related requests.
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult GetOrders()
{
var orders = new List<string> { "Order1", "Order2" };
return Ok(orders);
}
}
Step 4: Run the Application
Run the Product and Order services:
dotnet run --project ProductService
dotnet run --project OrderService
Run the API Gateway:
dotnet run --project ApiGateway
Test the Gateway:
- Access
http://localhost:5000/products
to get products from the Product Service. - Access
http://localhost:5000/orders
to get orders from the Order Service.
Conclusion
Using an API Gateway like Ocelot in .NET simplifies client interactions with multiple microservices. It handles cross-cutting concerns, making the architecture more scalable and manageable. This guide demonstrated how to set up an API Gateway using Ocelot, create downstream services, and route requests through the gateway. By adopting this pattern, you can achieve a more robust and maintainable microservice architecture.
You may also like : https://medium.com/@siva.veeravarapu/load-balancer-in-net-microservice-architecture-02999ad47062