Microservices Architecture with ASP.NET Core

Implementing API Gateway Pattern using Ocelot

What is Microservices Architecture?

Microservices architecture is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API.

Benefits of Microservices:

API Gateway Pattern with Ocelot

Ocelot is a .NET API Gateway that provides routing, authentication, rate limiting, and other cross-cutting concerns for microservices architectures.

API Gateway
(Ocelot)
User
Service
Product
Service
Order
Service
Payment
Service
Auth
Service
Inventory
Service

Required NuGet Packages

Implementation Steps

1

Create API Gateway Project

Create a new ASP.NET Core Web API project and install the Ocelot package.

dotnet new webapi -n ApiGateway
cd ApiGateway
dotnet add package Ocelot
2

Configure Ocelot

Create an ocelot.json configuration file to define your routes and services.

{ "Routes": [ { "DownstreamPathTemplate": "/api/users", "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5001 } ], "UpstreamPathTemplate": "/users", "UpstreamHttpMethod": [ "Get" ] } ] }
3

Program.cs Setup

Configure Ocelot in your Program.cs file.

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("ocelot.json");
builder.Services.AddOcelot();
var app = builder.Build();
app.UseOcelot().Wait();
app.Run();
4

Create Microservices

Create individual microservices as separate ASP.NET Core Web API projects.

dotnet new webapi -n UserService
dotnet new webapi -n ProductService
dotnet new webapi -n OrderService
5

Configure Routing

Define all routes in the ocelot.json file to map incoming requests to appropriate microservices.

6

Add Authentication & Authorization

Implement JWT authentication in the API Gateway to secure your microservices.

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        // Configuration here
    });

Sample ocelot.json Configuration

{ "Routes": [ { "DownstreamPathTemplate": "/api/users", "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5001 } ], "UpstreamPathTemplate": "/users", "UpstreamHttpMethod": [ "Get" ], "AuthenticationOptions": { "AuthenticationProviderKey": "Bearer" } }, { "DownstreamPathTemplate": "/api/products", "DownstreamScheme": "https", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5002 } ], "UpstreamPathTemplate": "/products", "UpstreamHttpMethod": [ "Get", "Post" ] } ], "GlobalConfiguration": { "BaseUrl": "https://localhost:5000" } }