Build A .NET Core Microservice With Ocelot API Gateway

Introduction 

 
This article is about microservice architecture and is mainly focused on why microservice architecture has a leading edge over monolithic architecture. This article also describes how to develop a microservice in .NET Core 3.1 with API Gateway using Ocelot.
 

Microservices

 
Microservice architecture is an approach of developing a single application as a suite of small services, each runs independently and communicate with each other. It splits an entire application into a smaller set of interconnected services, instead of building a single monolithic application.
 
Microservice Communication
 
There are many protocols available for communication, depending on the communication type you want to use. If you're using a synchronous request/response-based communication mechanism, protocols such as HTTP and REST approaches are the best approaches.
 
If you're communicating between services internally (within your Docker host or microservices cluster), you can use asynchronous protocols, message-based communication mechanisms such as Azure bus service, AMQP, and so on.
 
Microservice vs Monolithic
 
Monolithic architecture is a traditional approach that deals with developing a single application as a whole, it's easy to develop and test, but the main concern of monolithic architecture comes while redeploying an application during an update. In monolithic architecture, a complete application needs to be redeployed for each and every update.
 
The other drawbacks include the fact that a bug in an application can completely bring down an entire application, and the application startup time takes too long because of its size. To overcome all the drawbacks of monolithic architecture, microservices come into play.
 
Now let's discuss how to create a microservices in .NET core 3.1 with API gateway. 
 
In this demo, I created a .NET Core 3.1 Web API using Entity framework core. In my upcoming article, let's look some in-depth concepts of EF core that includes the code first approach and the database first approach. In this demo, I simply used the code first approach for developing a web API.
 

Create an empty solution 

 
Usually, microservice architecture contains a single solution that contains many services. Hence, create a project in VS 2019, choose .NET core, and add an empty template.
 
Add a Web API and name it as Web Service 1
 
Add a web API project to an existing solution. Once it is added, You can find a web API service available under the solution. In this web API, the code first approach in EF core is used to create a database in SQL. If you need other actions to perform, add those as per requirement in your web API. 
 
Add a Web API and name it as Web Service 2
 
Add a web API project to an existing solution. Once it is added, You can find a web api service available under the solution. In this web api, Code first approach in EF core is used to create a database in SQL. Repeat the steps given above and create a web API project and name it as web service 2.
 

Ocelot 

 
Ocelot is a .NET API Gateway. Ocelot plays an important role in .NET core microservices and service-oriented architecture that need a unified point of entry into their system. Ocelot works by manipulating the HttpRequest object into a state specified by its configuration until it reaches a middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. 
 
Features of Ocelot
  • Routing
  • Service Fabric
  • Kubernetes
  • WebSockets
  • Authentication
  • Authorization
  • Load Balancing
Refer the link to learn more about Ocelot, documentation.
 
Create a Web API and add Ocelot.json
 
Add a web API project to an existing solution. Once it is added, you can find a web api service available under the solution. In this web API, we are going to perform gateway activities. To perform gateway activity, add a JSON file to this empty web API solution and give the details of upstream and downstream, as given in the below code.
  1. {    
  2.   "Routes": [    
  3.     {    
  4.       "DownstreamPathTemplate""/api/MicroserviceDemo",    
  5.       "DownstreamScheme""https",    
  6.       "DownstreamHostandPorts": [    
  7.       //  <-------------Local Host details ------------>  
  8.        //{    
  9.         //  "Host": "localhost",    
  10.         //  "Port": "44324"    
  11.         //}    
  12.         {    
  13.           "Host""appservice1.azurewebsites.net"    
  14.         }    
  15.     
  16.       ],    
  17.       "UpstreamPathTemplate""/service1",    
  18.       "UpstreamHttpMethod": [ "GET" ]    
  19.     },    
  20.     {    
  21.       "DownstreamPathTemplate""/WeatherForecast",    
  22.       "DownstreamScheme""https",    
  23.       "DownstreamHostandPorts": [    
  24.  //<-------------Local Host details ------------>  
  25.         //{    
  26.         //  "Host": "localhost",    
  27.         //  "Port": "44384"    
  28.         //},    
  29.         {    
  30.           "Host""appservice2.azurewebsites.net"    
  31.         }    
  32.         ],    
  33.       "UpstreamPathTemplate""/service2",    
  34.       "UpstreamHttpMethod": [ "GET" ]    
  35.     }    
  36.       
  37.   ]    
  38. }    
How does it work? 
 
API gateway act as an entry point of the request for the service endpoints registered. We can access the services directly through the API gateway without accessing the actual web API service endpoint.  
 
Here in this project, we have two services and we are going to access both the services via an API gateway without accessing the services actual endpoint.
 
Configure Ocelot 
 
Don't forget to configure ocelot in the program.cs, as given below in the code. 
  1. public static IHostBuilder CreateHostBuilder(string[] args) =>    
  2.             Host.CreateDefaultBuilder(args)    
  3.                 .ConfigureWebHostDefaults(webBuilder =>    
  4.                 {    
  5.                     webBuilder.UseStartup<Startup>();    
  6.                 })    
  7.            .ConfigureAppConfiguration((hostingContext, config) =>    
  8.            {    
  9.                config.AddJsonFile("oscelot.json");    
  10.            });    

Project Structure

 
This is how the project structure looks after performing all the above operations.
                                                                             
 
Run and Check in Local host 
 
The following outputs are obtained by running the services in the localhost. In this project, the API gateway process the incoming request of both registered services.
 
Both service 1 and service 2 are accessible via the API gateway:
 
Build A .Net Core Microservice With Ocelot API Gateway
 
Build A .Net Core Microservice With Ocelot API Gateway
 
Run and Check in Azure 
 
Now we can publish our microservice application in azure. We need to create a separate app service for each service and API gateway. As normal, Publish it directly from the VS 2019. The following outputs are obtained by running the services in Azure. Change the endpoints from the local host to Azure endpoints in ocelot.json before publishing the operation. In this project, the API gateway processes the incoming request of both registered services. 
 

Summary 

 
In this article, we discussed something interesting about microservice architecture and API gateway operations so on. In upcoming articles, we will discuss something more and in-depth about .NET core and Azure services.
 
Before saying goodbye to this article, I wish to share my mistakes and common errors I went through during this development. 
  • If you are using .NET core 3.1, Use Routes in ocelot.json file. In the new release of Ocelot, the reroutes are changed to routes. 
  • Kindly set a startup project as multiple projects and choose all projects in the list as start. 
  • In the Azure app service, enable https, if you enabled https in your project. 
Happy reading and coding!