Creating an API Gateway using Ocelot.NET & ASP.NET Core (.NET 5)

Dominique Kleeven
3 min readFeb 14, 2021

--

An API Gateway is an application/service that is responsible for forwarding/redirecting requests to a downstream service. It is a common practice in Microservice Architectures, however, it also enables you to combine multiple REST APIs provided by different applications into a single HTTP(S) address.

Tutorial Content

  • Creating a simple rest application to act as our downstream application. (Web API Template)
  • Creating the API Gateway which forwards the request to the downstream sample application.

Full Project can be found at https://github.com/dominiquekleeven/medium-apigateway-with-ocelot

Prerequisites

  • IDE of Choice
  • .NET Core 3.1 or .NET 5 SDK (Asp.net Core)

Creating the Sample Application

If you’re using Visual Studio or Rider this should be quite easy, all you have to do is to create a default ASP.NET Core project using the Web API template.

You can also find the SimpleAPI at https://github.com/dominiquekleeven/medium-apigateway-with-ocelot

Creating the API Gateway

  1. Create an empty ASP.NET Core Web Project.
  2. Install the Ocelot Nuget package

3. Update Program.cs

Your Program.cs should look like this

4. Create an ocelot.json file in your project's root directory. (same location as appsettings.json)

ocelot.json

{
"Routes": [
{
"DownstreamPathTemplate": "/WeatherForecast",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5000
}
],
"UpstreamPathTemplate": "/api/weather" ,
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:5003"
}
}

Quick explanation

DownstreamPathTemplate: the endpoint prefix of the downstream service.
DownstreamHostAndPoints: the downstream IP:PORT address. In this case, localhost:5000 which is the address, I’ll be running the SimpleAPI on.

Read the official documentation for more information

5. Change the gateway port numbers to prevent a startup error. (You can do this in the Properties/launchsettings.json file.

"applicationUrl": "https://localhost:5003;http://localhost:5002",

Start both applications (SimpleAPI and the Gateway)

Goto https://localhost:5003/api/weather
Which should forward your request to https://localhost:5001/WeatherForecast

And that’s about it. You can add as many downstream services as you want.

Don’t like using static addresses for your downstream services? Check out Consul, which easily integrates with Ocelot.net.

Check out my tutorial about integrating Consul with Ocelot.net

--

--

Dominique Kleeven
Dominique Kleeven

Written by Dominique Kleeven

Short coding tutorials & exploring tech topics.

No responses yet