Introduction
In the previous articles of this series, we discussed how to build the API Gateway in ASP.NET Core. In this article, we will discuss the service discovery module of Ocelot with Consul.
If you want to look at the previous articles of this series, please visit the links given below.
- Building API Gateway Using Ocelot In ASP.NET Core - Basic
- Building API Gateway Using Ocelot In ASP.NET Core - Authentication
- Building API Gateway Using Ocelot In ASP.NET Core - Logging
- Building API Gateway Using Ocelot In ASP.NET Core - Rate Limiting
- Building API Gateway Using Ocelot In ASP.NET Core - QoS
- Building API Gateway Using Ocelot In ASP.NET Core - Load Balancing
- Building API Gateway Using Ocelot In ASP.NET Core - Service Discovery (Eureka)
Step 1
Running up the Consul at first.
For the demonstration, I will use Docker to run up an instance of Consul.
- docker run -p 8500:8500 consul
After running up, we can get the following result.

Step 2
Create an API service that should be registered in Consul.
For the demonstration, I will create two Web API projects with different port numbers but their service names are the same.
Write some code in controller.
- [Route("api/[controller]")]
- [ApiController]
- public class ValuesController : ControllerBase
- {
- // GET api/values
- [HttpGet]
- public ActionResult<IEnumerable<string>> Get()
- {
- var port = Request.Host.Port;
- return new string[] { "value1", "value2", port.Value.ToString() };
- }
- }
Then, we should register it to Consul. The following code shows you a sample way to do that.
- public static class AppExtensions
- {
- public static IServiceCollection AddConsulConfig(this IServiceCollection services, IConfiguration configuration)
- {
- services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(consulConfig =>
- {
- var address = configuration.GetValue<string>("Consul:Host");
- consulConfig.Address = new Uri(address);
- }));
- return services;
- }
- public static IApplicationBuilder UseConsul(this IApplicationBuilder app)
- {
- var consulClient = app.ApplicationServices.GetRequiredService<IConsulClient>();
- var logger = app.ApplicationServices.GetRequiredService<ILoggerFactory>().CreateLogger("AppExtensions");
- var lifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
- if (!(app.Properties["server.Features"] is FeatureCollection features)) return app;
- var addresses = features.Get<IServerAddressesFeature>();
- var address = addresses.Addresses.First();
- Console.WriteLine($"address={address}");
- var uri = new Uri(address);
- var registration = new AgentServiceRegistration()
- {
- ID = $"MyService-{uri.Port}",
- // servie name
- Name = "MyService",
- Address = $"{uri.Host}",
- Port = uri.Port
- };
- logger.LogInformation("Registering with Consul");
- consulClient.Agent.ServiceDeregister(registration.ID).ConfigureAwait(true);
- consulClient.Agent.ServiceRegister(registration).ConfigureAwait(true);
- lifetime.ApplicationStopping.Register(() =>
- {
- logger.LogInformation("Unregistering from Consul");
- consulClient.Agent.ServiceDeregister(registration.ID).ConfigureAwait(true);
- });
- return app;
- }
- }
We also should modify the Startup class to enable registration.





MJ EbrahimiPosted Sep 10, 2020, 3:06 PM
Good article. For the record, this article was added to this awesome repository. https://github.com/mjebrahimi/Awesome-Microservices-NetCore
Stan SrPosted Oct 29, 2019, 9:44 AM
Hi, this line alway returns null var addresses = features.Get<IServerAddressesFeature>();
Vivek NegiPosted Oct 14, 2019, 11:55 AM
Addresses returned null in my case.
Venky VenkataramanPosted Aug 27, 2019, 6:05 PM
Brilliant. Big fan of your tutorials. Excellent.
Ravian ReaverPosted Aug 12, 2019, 1:31 PM
Really glad that you did a tutorial on this! Thank you (: