Introduction
In this article, you will learn an easy way to build your API Gateway using Ocelot in ASP.NET Core. Maybe you will ask the question, what is API Gateway.
Let's take a look at the below screenshot first.
The above screenshot can help you understand it clearly.
API Gateway is an entry to our systems. It contains lots of things, such as Routing, Authentication, Service discovery, Logging .etc.
Ocelot
Ocelot is aimed at people using .NET running a micro-services / service orientated architecture who need a unified point of entry into their system. You can visit this project’s Github page to find more information.
I will use a simple demo to show you how to use Ocelot.
Let's begin!
Step 1
Create three projects at first.
Project Name |
Project Type |
Description |
APIGateway |
ASP.NET Core Empty |
entry of this demo |
CustomersAPIServices |
ASP.NET Core Web API |
API Service that handles something about customers |
ProductsAPIServices |
ASP.NET Core Web API |
API Service that handles something about products |
Step 2
Finish the two API services at first. Create a CustomersController in CustimersAPIServices project.
- [Route("api/[controller]")]
- public class CustomersController : Controller
- {
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new string[] { "Catcher Wong", "James Li" };
- }
-
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return $"Catcher Wong - {id}";
- }
- }
In order to specify the App URL of this service, we should add UseUrls in the Program class.
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup<Startup>()
- .UseUrls("http://localhost:9001")
- .Build();
Create a ProductsController in ProductsAPIServices project.
- [Route("api/[controller]")]
- public class ProductsController : Controller
- {
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new string[] { "Surface Book 2", "Mac Book Pro" };
- }
- }
Edit the Program class to add UseUrls as well.
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup<Startup>()
- .UseUrls("http://localhost:9002")
- .Build();
Note
You also can specify the App URL in the Project Options page.
Step 3
Run the customer service and product service.
Open two terminals and use the "dotnet run" command to start them.
As you can see, customer service is listening to http://localhost:9001 and product service is listening on http://localhost:9002.
Open the browser to verify whether the service is OK.
Luckily, everything was going well.
Step 4
Now, we should turn to APIGateway project. We should install Ocelot package at first.
Install-Package Ocelot
After installing this package, you can find some dependence on it.
Step 5
Add a configuration.json file.
- {
- "ReRoutes": [
- {
- "DownstreamPathTemplate": "/api/customers",
- "DownstreamScheme": "http",
- "DownstreamHost": "localhost",
- "DownstreamPort": 9001,
- "UpstreamPathTemplate": "/customers",
- "UpstreamHttpMethod": [ "Get" ]
- },
- {
- "DownstreamPathTemplate": "/api/customers/{id}",
- "DownstreamScheme": "http",
- "DownstreamHost": "localhost",
- "DownstreamPort": 9001,
- "UpstreamPathTemplate": "/customers/{id}",
- "UpstreamHttpMethod": [ "Get" ]
- },
- {
- "DownstreamPathTemplate": "/api/products",
- "DownstreamScheme": "http",
- "DownstreamPort": 9002,
- "DownstreamHost": "localhost",
- "UpstreamPathTemplate": "/api/products",
- "UpstreamHttpMethod": [ "Get" ]
- }
- ],
- "GlobalConfiguration": {
- "RequestIdKey": "OcRequestId",
- "AdministrationPath": "/administration"
- }
- }
This file is the configuration of the API Gateway. There are two sections to the configuration- an array of ReRoutes and a GlobalConfiguration.
The ReRoutes are the objects that tell Ocelot how to treat an upstream request. The Global configuration is a bit hacky and allows overrides of ReRoute specific settings.
Take this part to explain the ReRoutes section.
- {
- "DownstreamPathTemplate": "/api/customers/{id}",
- "DownstreamScheme": "http",
- "DownstreamHost": "localhost",
- "DownstreamPort": 9001,
- "UpstreamPathTemplate": "/customers/{id}",
- "UpstreamHttpMethod": [ "Get" ]
- }
The items start with Downstream which means that our request will be forwarded to http://localhost:9001/api/customers/{id}.
The items start with Upstream which means that we should use HTTP GET method with /customers/{id}` to visit this service.
Step 6
Edit the Startup class so that we can use Ocelot in this project.
- public class Startup
- {
- public Startup(IHostingEnvironment env)
- {
- var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
- builder.SetBasePath(env.ContentRootPath)
-
- .AddJsonFile("configuration.json", optional: false, reloadOnChange: true)
- .AddEnvironmentVariables();
-
- Configuration = builder.Build();
- }
-
-
- public IConfigurationRoot Configuration { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- Action<ConfigurationBuilderCachePart> settings = (x) =>
- {
- x.WithMicrosoftLogging(log =>
- {
- log.AddConsole(LogLevel.Debug);
-
- }).WithDictionaryHandle();
- };
- services.AddOcelot(Configuration, settings);
- }
-
-
- public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- await app.UseOcelot();
- }
- }
Don't forget to add the configuration.json file to the Configuration .
Step 7
This is a very important step to configure Ocelot.
We should create a new instance of IWebHostBuilder. And, don't use var here !!!
- public class Program
- {
- public static void Main(string[] args)
- {
- IWebHostBuilder builder = new WebHostBuilder();
- builder.ConfigureServices(s =>
- {
- s.AddSingleton(builder);
- });
- builder.UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseStartup<Startup>()
- .UseUrls("http://localhost:9000");
-
- var host = builder.Build();
- host.Run();
- }
- }
We also specify the App URL of the API Gateway here.
Step 8
Run your API Gateway.
As you can see, our API Gateway is running on http://localhost:9000
We open the browser to visit our services.
When visiting http://localhost:9000/api/products, we will get the result from http://localhost:9002/api/products .
When visiting http://localhost:9000/customers, we will get the result from http://localhost:9001/api/customers .
When visiting http://localhost:9000/customers/1, we will get the result from http://localhost:9001/api/customers/1.
Here is the source code you can find on my Github page.
Summary
This article introduced how to build API Gateway via Ocelot. Hope this will help you!
By the way, this is a very easy demo; there are some important things I did not mention in this article, such as Service discovery, Authentication, and Quality of Service