Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)

Introduction

 
In the previous articles of this series, we discussed how to build the API Gateway in ASP.NET Core. Usually, when using Ocelot, we will store the configuration in the configuration file. It's very convenient for us to modify it during development.
 
However, after we publish it, we can not modify them it directly due to some reasons!
 
Ocelot also allows us to store the configuration in the consul so that we can modify the configuration via consul. And in this article, we will discuss how to do it.
 
If you want to look at the previous articles of this series, please visit the links given below.
 
Step 1
 
Running up the Consul at first.
 
For the demonstration, I will use Docker to run up an instance of Consul.
  1. docker run -p 8500:8500 consul  
Step 2 
 
Create a downstream API service that will be used by the API gateway.
 
We just add some actions and both of them are returning a string. 
  1. [Route("api/[controller]")]  
  2. [ApiController]  
  3. public class ValuesController : ControllerBase  
  4. {  
  5.     // GET api/values  
  6.     [HttpGet]  
  7.     public ActionResult<string> Get()  
  8.     {  
  9.         return "value";  
  10.     }  
  11.   
  12.     // GET api/values/demo1  
  13.     [HttpGet("demo1")]  
  14.     public ActionResult<string> GetDemo1()  
  15.     {  
  16.         return "demo1";  
  17.     }  
  18.   
  19.     // GET api/values/demo2  
  20.     [HttpGet("demo2")]  
  21.     public ActionResult<string> GetDemo2()  
  22.     {  
  23.         return "demo2";  
  24.     }  
  25.   
  26.     // GET api/values/demo3  
  27.     [HttpGet("demo3")]  
  28.     public ActionResult<string> GetDemo3()  
  29.     {  
  30.         return "demo3";  
  31.     }  
  32. }  
The next step is to build the API gateway.
 
Step 3
 
Creating an empty ASP.NET Core project and add the following two packages via .NET Core CLI.
  1. dotnet add package Ocelot --version 13.5.2  
  2. dotnet add package Ocelot.Provider.Consul --version 13.5.2  
Add a new JSON configuration file named ocelot.json. And here is the contents of it.
  1. {  
  2.   "ReRoutes": [  
  3.     {  
  4.       "DownstreamPathTemplate""/api/values",  
  5.       "DownstreamScheme""http",  
  6.       "DownstreamHostAndPorts": [  
  7.         {  
  8.           "Host""localhost",  
  9.           "Port": 8989  
  10.         }  
  11.       ],  
  12.       "UpstreamPathTemplate""/values",  
  13.       "UpstreamHttpMethod": [ "GET" ]  
  14.     },  
  15.     {  
  16.       "DownstreamPathTemplate""/api/values/demo1",  
  17.       "DownstreamScheme""http",  
  18.       "DownstreamHostAndPorts": [  
  19.         {  
  20.           "Host""localhost",  
  21.           "Port": 8989  
  22.         }  
  23.       ],  
  24.       "UpstreamPathTemplate""/values/demo1",  
  25.       "UpstreamHttpMethod": [ "GET" ]  
  26.     }  
  27.   ],  
  28.   "GlobalConfiguration": {  
  29.     "ServiceDiscoveryProvider": {  
  30.       "Host""localhost",  
  31.       "Port": 8500,  
  32.       "PollingInterval" : 5000  
  33.     }  
  34.   }  
  35. }  
 As you can see, the ReRoutes section only contains two nodes.
 
The configuration means that we can only access http://localhost:8989/api/values and http://localhost:8989/api/values/demo1 via API gateway.
 
But we also configure ServiceDiscoveryProvider node in GlobalConfiguration section.
 
This is the most important step for us to store the configuration in the consul that can tell Ocelot the address of consul and how often to read the configuration from consul KV.
 
And the default value of PollingInterval is 1000ms, here we modify it to 5000ms.
 
At last, we should configure Ocelot in the Program class.
  1. public class Program  
  2. {  
  3.     public static void Main(string[] args)  
  4.     {  
  5.         CreateWebHostBuilder(args).Build().Run();  
  6.     }  
  7.   
  8.     public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>  
  9.         WebHost.CreateDefaultBuilder(args)  
  10.          .UseUrls("http://*:9000")  
  11.          .ConfigureAppConfiguration((hostingContext, config) =>  
  12.          {  
  13.              config  
  14.                  .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)  
  15.                  .AddJsonFile("ocelot.json")  
  16.                  .AddEnvironmentVariables();  
  17.          })  
  18.         .ConfigureServices(services =>  
  19.         {  
  20.             services.AddOcelot()  
  21.                 .AddConsul()  
  22.                 // Store the configuration in consul  
  23.                 .AddConfigStoredInConsul();  
  24.         })  
  25.         .Configure(app =>  
  26.         {  
  27.             app.UseOcelot().Wait();  
  28.         });  
  29. }  
After running up the API gateway, we can find out that there is a new KV item in the consul named InternalConfiguration. And the value is the full information of the configuration.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
 
We can change the default name InternalConfiguration to whatever you want via ConfigurationKey.
  1. "GlobalConfiguration": {  
  2.     "ServiceDiscoveryProvider": {  
  3.         "Host""localhost",  
  4.         "Port": 8500,  
  5.         "ConfigurationKey""A_Gateway"  
  6.     }  
  7. }  
 For the above sample, the name of consul KV should be A_Gateway.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
 
Go back to the terminal, there are many polling log per 5000ms.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
 
But at this time, we also can not access http://localhost:8989/api/values/demo2 via API gateway.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
 
We can add a new ReRoute item to consul KV item, so that we can access it.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
 
After saving the configuration in consul, we can visit it right now.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
Here is the terminal log when we access the API Service via API gateway.
 
Building API Gateway Using Ocelot In ASP.NET Core - Configuration (Consul)
 
Here is the source code you can find in my GitHub page.

Summary

 
This article introduced how to store the configuration in consul when using Ocelot.
 
I hope this helps you.