Implementing API Gateway Pattern using Ocelot
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.
Ocelot is a .NET API Gateway that provides routing, authentication, rate limiting, and other cross-cutting concerns for microservices architectures.
Create a new ASP.NET Core Web API project and install the Ocelot package.
dotnet new webapi -n ApiGatewaycd ApiGatewaydotnet add package 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" ]
}
]
}
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();
Create individual microservices as separate ASP.NET Core Web API projects.
dotnet new webapi -n UserServicedotnet new webapi -n ProductServicedotnet new webapi -n OrderService
Define all routes in the ocelot.json file to map incoming requests to appropriate microservices.
Implement JWT authentication in the API Gateway to secure your microservices.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
// Configuration here
});
{
"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"
}
}