What is Ocelot Gateway? (ASP.NET Core Set Up and Pilot Project)

Fatih GÜRDAL
8 min readApr 24, 2024

--

What is Ocelot Gateway?

Ocelot is a strong instrument that simplifies API management by reducing complexity in microservice architectures. While organizing communication between services, this API gateway solution provides the advantage of managing all requests from a single point. Ocelot has such significant functions as authorization, security control and traffic management while routing incoming requests.What’s more, the flexible structure of Ocelot lets it work with different. protocols and provides application developers with a scalable, secure and high performance API management experience. To sum up, it offers a gateway solution for not only small scale but also large scale projects.

Microservice Architectures and API Gateway Concept

As one of the vital elements at the centre of microservices architectures, the API gateway occupies an important position in facilitating the communication of complex systems and providing central point of control. In this sense, Ocelot is a reliable solution which has been designed to manage incoming requests, implement security measures and realize efficient traffic management by creating a bridge between different microservices, thereby contributing to the efficient operation of microservice architectures and making inter-system communication crystalline.

Key Features and Working Principles of Ocelot

Ocelot, while working as an API gateway, also facilitates communication between different services by offering a flexible and modular structure. Its working principle is based on processing incoming requests according to predefined routing and forwarding them to the relevant services in line with predefined routing. The library consists of a number of features, and it receives requests from clients, directs them, filters them and provides communication between services. Besides, it draws attention thanks to its additional functionality such as monitoring and logging communication with clients and services. By means of the flexible configuration capabilities of Ocelot, a simple and straightforward structure can be set in order to route incoming requests, and thus, this gives developers a wide range of customization possibilities.

How to Install and Use?

Our pilot project will be simple, flexible and in a way to communicate with multiple services.

At first, we will install Ocelot and the libraries which will make our configuration easier. Depending on the .net version you will use, the version of the packages may vary, so we will continue without specifying the version.

By adding 3 services behind the API Gateway, it will redirect all requests from outside to a single Ocelot API project. Requests will then be directed to the relevant services. Our sample scheme will be as shown below;

We will create 4 projects. There will be Ocelot in one project. 1 or 2 projects are fine. For clarity, we will do it with 3.

· APIGateway

· AuthService

· ProductService

· BasketService

We install 3 libraries for Ocelot, configuration and swagger integration for API Gateway Project.

nuget install MMLib.Ocelot.Provider.AppConfiguration

nuget install MMLib.SwaggerForOcelot

nuget install Ocelot

Before the builder completes building, the relevant configuration definitions are added. The Folder specifies the directory of the json file where we will do the Ocelot settings.

builder.Configuration.AddOcelotWithSwaggerSupport(options =>
{
options.Folder = "OcelotConfiguration";
});
builder.Services.AddOcelot(builder.Configuration).AddAppConfiguration();
builder.Services.AddSwaggerForOcelot(builder.Configuration);

After the builder has completed building, the UseSwaggerForOcelotUI definition is added to import the swagger documents of the projects connected to in the gateway. UseOcelot, is added for the standard Ocelot library.

app.UseSwaggerForOcelotUI(opt =>
{
opt.PathToSwaggerGenerator = "/swagger/docs";
});
app.UseOcelot().Wait();

The details I have mentioned above are for Ocelot alterations. When we add those lines above to an empty ASP.NET Core project, the final Program.cs will look like this.

Now it is time to define the JSON files for Ocelot configurations.

We can enter a separate JSON configuration in each project, but I recommend defining it in separate files, as it is more readable and there is a possibility that these configurations can be expanded in future projects. We can define the auth service for all endpoints, but since we are making a simple gateway example now, we will route all endpoints with a single configuration file.

Here, I specify the parameters we will define:

· SwaggerKey: They key which will receive the Swagger configuration of the service that we will connect to. Below, we will associate this setting with the ocelot.SwaggerEndpoints.json file.

· DownstreamPathTemplate: When the request is received, we specify the format that the request will be routed to the Auth service.

· ServiceName: When we are defining the address of the Auth service on the internal network in appsettings.json, the key will match.

· UpstreamPathTemplate: We will define the prefix/url which we will use in order to receive the incoming requests to the gateway. When there is a single configuration, the prefix we add must be unique within the scope of the gateway. For instance, all requests starting with “/auth-gate/” will be directed to AuthService.

· UpstreamHttpMethod: Available HTTP methods are added. {everything} is used as a variable. You can type anything in the brackets, it is not a special keyword. We have used the same variable for Downstream and Upstream.

We can enter json configs accordingly for the other Product and Basket services.

Now, we will set up Swagger connections for the services we have added. Even though this step is not a mandatory one, I would like to indicate the capability of it.

Let’s create a JSON file named ocelot.SwaggerEndpoints.json in OcelotConfiguration file. Then, let’s add project-specific Swagger configurations into this file. Usually these configurations are the same for all projects. The purpose here is to specify the location of swagger.json by associating it with the corresponding Swagger key. Thus, it lets the gateway to make it connected projects look like its own Swagger documentation. In runtime, it gets the settings from the relevant swagger.json endpoint and presents them in a single project.

We have created 3 services so far and we have made the Swagger settings of these services.

However, we haven’t told where to find Product, Basket and Auth services. We could determine this information in the files of ocelot.product.json, ocelot.auth.json and ocelot.basket.json. However, under the assumption that these base URLs will not remain constant and that this information will depend on Ocelot configurations, we will move this dependency to the general settings of the project, such as appsettings.json. This is not an obligation but an alternative.

For example, in a web application in Azure Portal, you can change any feature in the Configuration tab without redeploying your application.

We will define the DownstreamPath (the addresses of BaseUrl) of Product, Basket and Auth services here. When Ocelot receives a request, it will redirect it to these addresses and call the relevant services.

Thus, if the addresses of our related services change over time, we can change the addresses by updating the appsettings.json file from the cloud services that we use. In order to get appsettings.json from the file of DownstreamPath, we need to add the ocelot.global.json file to the OcelotConfiguration index, just like the other JSON files, and ekleyip, assign AppConfiguration as the provider.

Our next steps are to create these three services and add sample endpoints to them. However, we don’t need to make any specific configuration adjustments for Ocelot, so you can create the sample web API projects. You just need to edit your launchSettings.json file to serve over ports 7001, 7002 and 7003 when these services are launched, or set the URLs when you launch the applications.

The sample project is available at this link

I use Rider IDE and I have added the Compound feature to start multiple projects. Different IDEs have similar features too; you can start HTTP ones by selecting projects from their profiles. downstreampath links in appsettings.json file are defined as default in the HTTP profiles.

Start the project and when we open the Swagger address of our Gateway project as /swagger in our browser, we will see a screen as shown above. Since we have integrated Swagger configurations with Ocelot, you will be able to switch between the Swaggers of Auth, Product and Basket services that we have connected from the upper right corner, and you will be able to see and use all endpoints.

One of our goals was to create an example to see the requests made to other services through Gateway. The Swagger, the configuration we made in the ocelot.SwaggerEndpoints.json file, pulls the relevant JSON over the path we specified and imports it at runtime. If the Swagger of the relevant service does not open, it means that we could not find the service at the address we specified as downstreampath. Seeing this Swagger is actually a proof that the connection has been successfully established.

Our expectation here is that all the requests starting with /auth-gate/*** should be redirected to downstreampath address that we specified in appsettings. The address looks like this;http://localhost:7002/api/***. As you remember, we specified these settings in the file of ocelot.auth.json.

When we make a request to auth-gate/Auth/GetUser without generating a token, we get the http error code 401 as expected.

At the moment, I’m getting 200 OK responses to the request I sent using the token I got with the GetToken tip. With the simple configuration we have made, we see that all requests routed through the gateway are shown by tests with the Authorization header.

ProductService

Product Service

BasketService

BasketService

We integrated 3 services with 1 API Gateway. In this article, we have implemented examples with AuthService in two different scenarios, with and without a session requirement. We also explained the Swagger configurations of the 3 connected services in detail. We have completed our sample project by adding an endpoint that returns dummy data to the other two services.

In conclusion, Ocelot is a powerful tool reducing the complexity of microservice architectures and greatly simplifies API management. Thanks to its flexible structure, modular design and constantly evolving features, it offers developers a wide range of customization and adaptability. It enables impeccable communication between different services, which allows microservice-based applications to be more effective and sustainable. You can manage your microservices from a single point and easily realize redirections as you wish. In the article, I tried to present a concrete example with simple installation and multiple service examples. However, Ocelot’s capabilities are not limited to these; it offers various alternatives to different needs (e.g. Load balancing, SignalR WebSocket, etc.).

Read this article in Turkish

--

--