You probably already have solved this, so this is meant for all the other developers looking for a solution to this. Below are two ways of adding the Ocelot configuration.
- Add a new
JSON file
in your project named ocelot.json
and add your configuration for ocelot inside.
- The file
ocelot.json
has to be registered in Program.cs
in order for Ocelot to load the configuration for your API Gateway.
Below are two examples of how you can register your Ocelot configuration.
1. Adding Ocelot configuration without environment check
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("ocelot.json")
.Build();
builder.Services.AddOcelot(configuration);
var app = builder.Build();
await app.UseOcelot();
app.MapGet("/", () => "Hello World!");
app.Run();
As you can see we load the configuration from ocelot.json by using .ConfigurationBuilder()
. We then parse the configuration to the method for adding Ocelot to the service container before registering it's middleware.
2. Add Ocelot configuration for the current environment
I tend to have multiple environments for production, testing, local development, etc... instead of re-writing/updating the configuration loader with the specific configuration file for Ocelot, we can do it by checking what environment we are running.
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile($"ocelot.{builder.Environment.EnvironmentName}.json", true, true)
.Build();
builder.Services.AddOcelot(configuration);
var app = builder.Build();
await app.UseOcelot();
app.MapGet("/", () => "Hello World!");
app.Run();
In the code above we use IHostEnvironment
to get the current environment name. We can then use string interpolation to dynamically insert the environment name into the string of our ocelot configuration file.
For this to work, you would have to add a new configuration file for each environment like this:
ocelot.json
├─ ocelot.Development.json
├─ ocelot.Local.json
├─ ocelot.Test.json