0% found this document useful (0 votes)
3 views

Microservices Using ASP.net Core - Dot Net Tutorials

This document provides a comprehensive overview of Microservices using ASP.NET Core, detailing their architecture, advantages, and comparison with Monolithic architecture. It explains the need for Microservices, their modular approach, and the role of API Gateways, specifically Ocelot, in managing microservices. Additionally, it includes practical steps for creating Microservices and an API Gateway in ASP.NET Core.

Uploaded by

hareeshvege224
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Microservices Using ASP.net Core - Dot Net Tutorials

This document provides a comprehensive overview of Microservices using ASP.NET Core, detailing their architecture, advantages, and comparison with Monolithic architecture. It explains the need for Microservices, their modular approach, and the role of API Gateways, specifically Ocelot, in managing microservices. Additionally, it includes practical steps for creating Microservices and an API Gateway in ASP.NET Core.

Uploaded by

hareeshvege224
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Microservices using ASP.

NET Core
Back to: ASP.NET Core Web API Tutorials

Microservices using ASP.NET Core Application with


Examples
In this article, I will explain Microservices using ASP.NET Core Application with Examples. At
the end of this article, you will understand the following pointers.

1. Understanding Microservices using ASP.NET Core

2. What are Microservices?

3. Need for a Microservice

4. Advantages of Microservices

5. Difference between Monolith Architecture and Microservice

6. Microservices Architecture

7. Understanding API Gateway (Ocelot Gateway with example)

8. Features of API Gateway

9. Creating Microservices in ASP.NET core

10. Creating an API Gateway in ASP.NET Core

11. Creating API Gateway Project using Ocelot

12. Configure API Gateway and Integrate Microservices

13. Configuring Ocelot Routes in ASP.NET Core

14. Testing Microservices

15. Testing Microservice through API Gateway

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 1 of 64
:
Microservices using ASP.NET Core

In this growing, fast-paced world, the amount of data and internet usage are proportionally
increasing, and so more reliable and fast-responding software systems are required; unlike the
older way of application development in Monolithic architecture, which causes high maintenance
cost, more downtime during upgrades made to existing monolithic architected software is not
reliable. So, the Microservices Architecture of developing applications came into the picture.

Earlier software architecture build contains all business functionalities, Database calls, and UI
designed in a single bundle. Like ASP.NET Webforms, MVC is a collection of single projects.

It has its disadvantages, and the larger the application grows, the harder it is to resolve the
technical bugs/problems quickly and to update the app with the new features. The Microservice
architecture-based approach for building applications helps solve these real-time issues and
provides more space for agile development methods and faster application response.

What are Microservices?

Microservices are the architectural approach to building applications from small to large-scale
applications. With this architectural approach, an application is broken down into the smallest
components, independent of each other. Unlike Monolithic architecture, where all the functionalities
are targeted to build into a single project/application, Microservices helps to separate functionalities
to develop in a more modular way, and all modules work together to accomplish the specific
targeted tasks.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 2 of 64
:
Need for a Microservice

This architectural approach to developing software gives more modularity, is lightweight, and has
the ability to share similar functionalities across multiple applications. It is a major way of designing
and optimizing app development towards a cloud-native model.

To develop quality software, the faster development process for change in existing software
features makes it easy to tackle any runtime issues after deployment into production. As we have
challenges in every positive idea, Microservices also have challenges like managing them and
Galaxy
aligning them to work without A35because
downtimes 5G we maintain them in different servers and have to
deal with the data and databases they use for transactions.
Samsung

Advantages of Microservices

Microservices give development teams and testers a faster approach through distributed
development. It provides the ability to develop multiple Microservices simultaneously. This means
more developers working on the same app but different functional modules simultaneously, which
results in less deliverable time of application to the client. Below are some critical points you can
observe positively in Microservices.

Faster Development

Since the application is designed into smaller modules, development time is shortened, and a
microservices architecture supports a more agile development process. Multiple teams can work on

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 3 of 64
:
each module/feature to develop and deliver separately.

High scalability

As user demand for some services in the application grows, you can deploy those services across
multiple servers and infrastructures to meet your needs. As much as the usage of services
increases by end-users, the deployment and extension of Microservice can be handled by load
balancing.

Resilient & Independency

The independent services, after properly developed and orchestrated, do not impact one another.
This means that if one service fails to work, the whole app won’t go down, unlike the monolithic
application model.

Easy of Deployment

Because microservice-based applications are more modular than traditional monolithic applications,
the problems with application deployments and application downtimes are reduced.

Accessibility for Development

Since the larger app is broken down into smaller modules, developers can easily understand,
update, and enhance the new changes, which results in fast development cycles if planned with
agile development methodologies.

More open

Microservices are not a particular language/technology-dependent, developers are free to choose


any best language and technology. In our current article, we will discuss more about the .Net
technology stack.

Difference between Monolith Architecture and Microservice.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 4 of 64
:
Monolith Architecture

First, we will understand the traditional way of building applications called Monolith Architecture, the
widely used architectural pattern while developing applications. Still, we can see these architecture
applications exist in the real world, and it is designed in a way that the entire application built is
ultimately a single piece, no matter how much you try to de-couple them by using Patterns and tiers
– 1/2/3. All the services or business functionalities would be tightly coupled within the single
Solution. The major thing to note is that while publishing the application, you would have to deploy it
to a single server only.

While it is still an effective way to build applications, some drawbacks are associated with Monolith
Architecture. Any small to midscale Applications would do just fine with this Architecture. Still, when
you scale up further to extend the capabilities of existing software, you would have to make a few
compromises and face whole application downtimes while deploying new versions/bug fixes.

Here is a diagrammatic representation of the Monolith Architecture.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 5 of 64
:
From the above diagram, you can observe different logic or layers you want to integrate with your
application are consolidated into a part of the single application itself. Thus, it is a big problem to
maintain and add a new feature and deployment of the application in this architecture.

Microservice Architecture

As we mentioned, using Microservice architecture, the application is divided into various


components or modules, each serving a particular purpose. These components are called
Microservices all to gather. These components are not dependent on the application itself. Each of
these components is truly independent in all technical manners. Because of this robust separation,
you can have separately dedicated Databases for each component, i.e., Microservice, and deploy
them to separate Hosts and servers.

Microservice Vs. Monolith Architecture

Monolithic Microservices

Dependent & compounded project Multiple Services are developed with a single
development of User Interface, Business purpose each.
Functional Components, and Database Logic.

Single Database due to complex coupled Dedicated Database for each microservice
development due to modularity.

Single programming Language dependency for Ability to choose multiple


the Backend (Business logic) technologies/languages for each
microservice.

The solution has to be deployed into a single Each of the Microservices can be deployed
Server. Physical Separation of deployment and anywhere on the web with ease.
maintenance is complex.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 6 of 64
:
Different business functionalities, technically Loosely Coupled Architecture because of the
called modules or components, will be tightly modular approach.
coupled to the application itself.

Microservices Architecture

A Brief Explanation of Microservice Architecture

We will discuss this here with a small example. Imagine we will build a School Management
Application in ASP.NET Core, which has the functionalities to handle Student Admission and
Attendance systems.

The monolith Approach would be to Build a Single MVC project Solution on Visual Studio and then
separate the functionalities via Layers / Tiers. Thus, you would probably have Projects like Data
Access Layer, Business Function Layer, View, etc.

Then, these Layers/ Tiers are just at the level of code organization and are efficient only while
developing. When you finish the application, you must publish them to a single server where you
can no longer see the separation concerns. A small change in any functionality has a heavy impact
on the whole application because of re-deployment to the server. The whole application has to
move to downtime and go through several unit tests to ensure that the new fix/enhancement did not
break existing functionalities.

But if you had followed a Microservice Architecture, you would have made Separate Components
for Student Admission, Student Attendance, etc. That means you have 2 different API Projects
specific to what a Student Admission Endpoint and a Student Attendance Endpoint needs. Now,
these different APIs (Microservices) can be deployed anywhere in the Web world and don’t need to
get deployed along with the Main Application. You can create a clean separation and physically
decouple the Application into various parts.

The below diagram illustrates a Microservice Architecture.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 7 of 64
:
In the above picture, we can see the Client UI application, either developed in .Net technology or
Android or IOS or Angular, etc., will interact with our decoupled APIs called Microservices
developed in .NET CORE technology, and they are deployed on multiple servers.

Prerequisites

If you don’t have knowledge on how to build the API in a .NET CORE, please visit this page
https://dotnettutorials.net/course/asp-net-core-web-api-tutorials/

Understanding API Gateway (Ocelot Gateway with example)

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 8 of 64
:
API Gateway is a middleware layer that directs incoming HTTP request calls from Client
applications to specific Microservice without directly exposing the Microservice details to the Client
and returning the responses generated from the respective Microservice.

Ocelot is an Open-Source API Gateway for the .NET/Core Platform officially supported by
Microsoft. What it does is simple. It mimics masking multiple microservices existing so that the
client does not have to worry about the location of each and every Microservice.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 9 of 64
:
Microsoft and other tech giants for Microservice Management widely use Ocelot. The latest version
of Ocelot supports only .NET Core applications built on the 3.1 version and above.

Features of API Gateway

API virtualization: API Gateways act as a single point entry for all the microservices configured,
avoid direct availability of microservices to clients, and hide versioning details of microservices.

Serves as an additional layer of security microservices: API gateways prevent malicious


attacks by providing an additional layer of protection from attack vectors and hackers like SQL
Injection, XML Parser exploits, denial-of-service (DoS) attacks, and forged form data submissions.

Decreased microservice complexity: Authorization techniques such as JWT and other


development concerns can constitute more time for the development of each microservice. An API
gateway can handle these concerns independently and remove the development burden from your
API code.

Creating Microservices in ASP.NET core

We will build a simple Microservice Architecture in ASP.NET Core with API Gateways. We must
install Visual Studio 2019 with the latest .NET frameworks released by Microsoft to build a .NET
Core web API.

Visit this link https://visualstudio.microsoft.com/downloads/ to download the VS 2019 free


community edition, which is enough for learning purposes. The minimum system requirements are

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 10 of 64
:
Windows 8/10, RAM memory of 4GB, and at least a quad-core processor to avoid latencies while
installing and application build/ running. After installation is completed, launch the Visual Studio
2019 IDE.

Application Building Steps Wise

Creating ASP.NET Core Web API Project Using Visual Studio 2019

Now, we will create the ASP.NET Core Web API project using Visual Studio 2019. So, open Visual
Studio 2019 and then click on the Create a new project option, as shown in the below image.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 11 of 64
:
Once you click on the Create a new project option, the following Create a new project window will
open. Here, you can find two project templates for creating the ASP.NET Core Web API project.
One is using C# language, and the other one is using F# language. I will use C# as the
programming language, so I selected the project template that uses C# Language, as shown in the
image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 12 of 64
:
Once you click the Next button, the configure your new project window will open. Here, you need to
specify the Project name, Solution name, and the location where you want to create the project. I
am providing the Project name as StudentAdmissionManagement, the solution name as
SchoolManagementSystem, and finally, click on the Next button as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 13 of 64
:
Once you click on the Next button, it will open the Additional Information window. Here, you need to
select the Target .NET Framework version, the authentication Types. Whether you want to
configure HTTPS and enable Docker, select .NET Core 3.1 for now because it has long-term
support from Microsoft, select authentication type as None, check the Configure for HTTPS and
uncheck the Enable Docker checkboxes and then click on the Create button as shown in the below
image.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 14 of 64
:
Once you click on the Create button, it will create the ASP.NET Core Web API project with the
following file and folder structure. Initially, I created only one separate project for student admission
purposes, which can be considered as a single microservice that works for student admission.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 15 of 64
:
Let us create one more project under the solution, which is another microservice for the purpose of
student attendance. To do so, right-click on the solution and then select the Add => New Project
option from the context menu, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 16 of 64
:
Once you click on the Add => New Project option, it will open the Add New Project window. From
this window, select ASP.NET Core Web API (which uses C# language) and click on the Next button,
as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 17 of 64
:
Once you click on the Next button, it will open Configure your new project window. From this
window, provide the project name as StudentAttendanceManagement and click on the Next button,
as shown in the below image.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 18 of 64
:
Once you click on the Next button, it will open the Additional Information window. Here, Select .NET
Core 3.1 as the Target Framework, select the authentication type as None, check the Configure for
HTTPS, uncheck the Enable Docker checkboxes, and then click on the Create button as shown in
the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 19 of 64
:
Once you click on the Create button, it will add the new project to the existing solution. Now, our
solution contains two projects with the following file and folder structure.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 20 of 64
:
Now we have two microservices defined, one for Student Admission purposes and the other for
Student Attendance purposes.

Creating Models:

Now let’s create a model class to hold details of Admission and Attendance in both the projects,
respectively, and create a CRUD operation Controllers in each project under the Controllers folder.
So, please right-click on the StudentAdmissionManagement project, add a class file named
StudentAdmissionDetailsModel.cs, and then copy and paste the following code.

using System;
namespace StudentAdmissionManagement
{
public class StudentAdmissionDetailsModel
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public string StudentClass { get; set; }
public DateTime DateofJoining { get; set; }

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 21 of 64
:
}
}

Now, please right-click on the StudentAttendanceManagement project, add a class file named
StudentAttendanceDetailsModel.cs, and then copy and paste the following code.

namespace StudentAttendanceManagement
{
public class StudentAttendanceDetailsModel
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public double AttendencePercentage { get; set; }
}
}

Creating Controllers:

Now, let us create controllers, which are endpoints for microservices for defining CRUD operations.
Right-click on the Controllers folder of StudentAdmissionManagement and then select the Add =>
Controller option from the context menu, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 22 of 64
:
Once you select the Add => Controller option, then it will open the Add New Scaffolded Item
window. Here, first, select the API template and then select the Add Controller with read/write action
template and click on the Add button, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 23 of 64
:
Once you click on the Add button from the next window, provide the name of your controller. Here, I
am providing the name as StudentAdmissionController and clicking on the Add button, as shown in
the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 24 of 64
:
Once you click on the Add button, it will add the StudentAdmissionController within the
Controllers folder of your StudentAdmissionManagement project.

For the demonstration purpose, we create a GET endpoint with details of two students, which will
return details of two students to client request over HTTP GET. So, modify the
StudentAdmissionController as follows.

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 25 of 64
:
using System.Threading.Tasks;
namespace StudentAdmissionManagement.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentAdmissionController :
ControllerBase
{
// GET: api/<StudentAdmissionController>
[HttpGet]
public IEnumerable<StudentAdmissionDetailsModel>
Get()
{
StudentAdmissionDetailsModel admissionobj1 =
new StudentAdmissionDetailsModel();
StudentAdmissionDetailsModel admissionobj2 =
new StudentAdmissionDetailsModel();

admissionobj1.StudentID = 1;
admissionobj1.StudentName = "Adam";
admissionobj1.StudentClass = "X";
admissionobj1.DateofJoining = DateTime.Now;

admissionobj2.StudentID = 2;
admissionobj2.StudentName = "Brad";
admissionobj2.StudentClass = "IX";
admissionobj2.DateofJoining = DateTime.Now;

List<StudentAdmissionDetailsModel> listofobj
= new List<StudentAdmissionDetailsModel>
{
admissionobj1,
admissionobj2
};
return listofobj;
}
}
}

Now, Right-click on the Controllers folder of StudentAttendanceManagement and then select the
Add => Controller option from the context menu, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 26 of 64
:
Once you select the Add => Controller option, then it will open the Add New Scaffolded Item
window. Here, first, select the API template and then select the Add Controller with read/write
actions and click on the Add button, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 27 of 64
:
Once you click on the Add button from the next window, provide the name of your controller. Here, I
am providing the name as StudentAttendanceController and clicking on the Add button, as shown in
the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 28 of 64
:
Once you click on the Add button, it will add the StudentAttendanceController within the Controllers
folder of your StudentAttendanceManagement project. For the demonstration purpose, we created
a simple Get method for returning the two students’ attendance percentages on HTTP GET
requests. So, modify the StudentAttendanceController as follows.

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentAttendanceManagement.Controllers

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 29 of 64
:
{
[Route("api/[controller]")]
[ApiController]
public class StudentAttendanceController :
ControllerBase
{
// GET: api/<StudentAttendanceController>
[HttpGet]
public IEnumerable<StudentAttendanceDetailsModel>
Get()
{
StudentAttendanceDetailsModel attendanceObj1
= new StudentAttendanceDetailsModel();
StudentAttendanceDetailsModel attendanceObj2
= new StudentAttendanceDetailsModel();
attendanceObj1.StudentID = 1;
attendanceObj1.StudentName = "Adam";
attendanceObj1.AttendencePercentage = 83.02;

attendanceObj2.StudentID = 2;
attendanceObj2.StudentName = "Brad";
attendanceObj2.AttendencePercentage = 71.02;

List<StudentAttendanceDetailsModel> listObj =
new List<StudentAttendanceDetailsModel>
{
attendanceObj1,
attendanceObj2
};
return listObj;
}
}
}

Let’s build the solution and launch both the Web API services (Microservices) simultaneously. For
this, we have to set both projects as starting projects. For that, open the properties window of
Solution and then select the multiple startup projects radio button and set the action to start for both
projects, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 30 of 64
:
Running Applications and Showing Outputs

Click on the Start button, and then we get two browsers opened and point to the controllers from
browsers like below. Browser, by default, sends GET HTTP Verb.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 31 of 64
:
They returned the details as expected. So, this is how microservices are developed, and our two
microservices are available to serve the user requests over HTTP requests and responses. To test
Microservices with the Postman application, please refer to the Testing section provided at the end
of this learning path.

Till now, we have observed the implementation of independent APIs (Microservices), which hold
separate concerns of business functionalities. One is to get admission details of all the students,
and the other is to get the attendance percentage of all the students in examples, which are directly
exposed to the Client.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 32 of 64
:
Creating an API Gateway in ASP.NET Core

In this section, let’s implement an API gateway, which will be responsible for re-directing the
incoming request from the client (Browser / Postman App / any Client Application) to the
Microservice and returning the response to the client. Observe the following diagram, depicting role
of API Gateway,

Creating API Gateway Project using Ocelot

Let’s create a separate ASP.NET Core Web API project named SchoolAPIGateway, as we created

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 33 of 64
:
projects in the solution earlier. Once the project is created, it will look like the one below in the
Solution Explorer window.

Installing Ocelot package

Let’s install the Ocelot Package. This makes the project behave as an API gateway. To do so, click
on Tools => NuGet Package Manager => Package Manager Console option from the context menu,
as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 34 of 64
:
Once you open the Package Manager Console window, choose SchoolAPIGateway as the default
project and then type Install-Package Ocelot -Version 15.0.7 and press enter as shown in the image
below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 35 of 64
:
If you face installation issues due to a mismatch of .NET versions, you can try the different versions
of Ocelot, and you will find the versions on the official NuGet website.

https://www.nuget.org/packages/Ocelot/

After successful installation, you can see the Ocelot package in the packages folder, as shown in
the below image.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 36 of 64
:
Configure API Gateway and Integrate Microservices.

let’s configure the project and define the Microservices endpoints.

Configure Ocelot as a middleware

Let’s configure the Ocelot to work with our application. Go to the Program.cs class file of the
SchoolAPIGateway Project and change the CreateHostBuilder() method as follows.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 37 of 64
:
namespace SchoolAPIGateway
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args


=>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureAppConfiguration((HostingContext,
config) => {

config.SetBasePath(HostingContext.HostingEnvironment.ContentRootPa
.AddJsonFile("Ocelot.json", optional: false,
reloadOnChange: true);
});

}
}

In the above code, we are configuring the app to read the Ocelot.json file from the root directory of
the project, which we obtained from the HostingContext class. The Ocelot reads the route
configuration from the JSON config file. Through that, the ASP.NET Core 3.1 Application can
access the settings. Remember that we are yet to have created the Ocelot.json file. We will be
creating it after we have configured the Ocelot Middleware.

In the project, SchoolAPIGateway opens the Startup.cs class file and add Ocelot to the
ConfigureServices method by adding services.AddOcelot() statement. And in the Configure( )
method adds the Ocelot Middleware to the ASP.NET Core Application Pipeline as follows.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 38 of 64
:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace SchoolAPIGateway
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use


this method to add services to the container.
public void ConfigureServices(IServiceCollection
services)
{
services.AddControllers();
services.AddOcelot();
}

// This method gets called by the runtime. Use


this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 39 of 64
:
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.UseOcelot().Wait();
}
}
}

Configuring Ocelot Routes in ASP.NET Core

This is the most important part of configuring Gateway to reroute the incoming requests to a definite
API service. In the Ocelot.json file, you have to configure the Upstream / Downstream routes for the
API Gateways, which makes Ocelot understand the routes to redirect the requests to microservices.
Let’s understand the following terms.

1. DownstreamPathTemplate is the path of the actual endpoint in the Microservice to which


the API Gateway redirects the incoming request from the client.
2. DownstreamScheme is the scheme used by Microservice, which is HTTPS.
3. DownstreamHostAndPorts defines the location of the Microservice, where we will add the
host details and port number details.
4. UpstreamPathTemplate is the path directed to the Ocelot API Gateway exposed to send
requests from the client.
5. UpstreamHttpMethod is the supported HTTP Method by the API Gateway, such as
GET/PUT/POST/DELETE. Based on the Incoming HTTP Method, Ocelot forwards a similar
HTTP method request to the microservice as well.

Upstream and Downstream are the two terms you must be clear with. Upstream Request is nothing
but the Request sent by the Client to the API Gateway, and Downstream request is the request sent
to the specific Microservice by the API Gateway. All these are visualized from the API Gateway
perspective.

Let’s add a basic route setting so that you can understand how it works. We will start with Student
Admission and Student Attendance Microservices, which we built earlier. Let’s say the client wants

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 40 of 64
:
to get all the student’s admission and student attendance details via the API Gateway this time.

We have the URL for Student Admission Microservice, which we built earlier and tested in Browser

https://localhost:44381/api/StudentAdmission -> Downstream URL

https://localhost:44317/api/StudentAttendance -> Downstream URL

Create a new Ocelot.json file in the root directory of the SchoolAPIGateway Project. This file carries
the routing configurations needed for Ocelot. To do so, add a JSON file with the name Ocelot.json
into the root directory of the SchoolAPIGateway Project and then copy and paste the following code
into it.

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/StudentAttendance",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 44317
}
],
"UpstreamPathTemplate":
"/apigateway/AttendanceService",
"UpstreamHttpMethod": [ "GET", "PUT", "POST" ]
},
{
"DownstreamPathTemplate": "/api/StudentAdmission",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 44381
}
],
"UpstreamPathTemplate":
"/apigateway/AdmissionService",
"UpstreamHttpMethod": [ "GET", "PUT", "POST"]
}

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 41 of 64
:
]
}

Ocelot reads the JSON file and takes an Array of Route Objects. As the first element in the array,
let’s configure the Student Attendance Microservice with access to GET, PUT, and POST HTTP
Verbs. Here in the example project, we are currently using only GET HTTP Verb. Another
Microservice Student Admission is also added, similar to Student Attendance.

Let’s test it now. As per our configuration, we have to request the SchoolAPIGateway project-
defined Gateway API endpoints in UpstreamPathTemplate that is located at localhost:44389, which
you can find in the launchSettings.json file in the same project, i.e., SchoolAPIGateway as shown in
the below image.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 42 of 64
:
Build the entire solution. Now, there is one thing to change. We have 3 APIs now. Let’s set up the
solution so that all three APIs get launched when you run the application. Because we will need all
the APIs actively working to test the functionality.

To launch Multiple Startup Projects, Go to the Solution Properties window. Select the Multiple
Startup Projects radio button, set the Start option in the Action dropdown for each project, and then
click the Apply and OK buttons, as shown in the image below.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 43 of 64
:
At the route https://localhost:44389/apigateway/AdmissionService, we are expecting to get the
results directly from the microservice, which is located at localhost:44381. Now, navigate to
apigateway/AdmissionService, and you will get the following result as expected.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 44 of 64
:
And also, for /apigateway/AttendanceService in API Gateway, you will get results from Student
Attendance Microservice as expected, as shown in the below image.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 45 of 64
:
We have successfully developed API Gateways and created a Microservice Architecture in
ASP.NET Core.

Testing Microservices using the POSTMAN application

Postman is a web API testing tool that is easy to understand and effective in testing all kinds of
HTTP Verbs like POST, GET, PUT, DELETE, etc., along with multiple kinds of request headers.
Using Postman, we can submit HTTP requests for actual client applications using these
microservices / Web APIs. This is the official link where you can download the Postman application.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 46 of 64
:
https://www.postman.com/downloads/

Testing Microservices

Ensure that the Student Attendance and Student Admission microservices are running in Visual
Studio and are available to serve the client HTTP requests before requesting from the postman to
get the expected outputs. I gave the Student Attendance microservice URL directly into the
Postman and clicked the send button. We got the expected output with status 200 OK, which
means the client request is successfully resolved.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 47 of 64
:
And now, testing the other microservice, Student Admission, I have given the URL with a GET
request, and we received the expected result with status 200 OK.

Testing the Microservice through API Gateway

Now, we will try to test the API gateway URLs that we defined for calling Student Attendance
microservice and Student Admission Microservice.

Ensure that all three projects are running, SchoolAPIGateway project, Student Admission
Management, and Student Attendance Management, so that the First request sent to

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 48 of 64
:
SchoolAPIGateway will redirect to the respective microservice and get a response.

I have given the API gateway URL defined to get Student Attendance details in Postman with GET
and sent the request. We received the expected output.

Similarly, I have initiated the request to the API gateway URL defined to get Student Admission
details in Postman with GET and sent the request, and We received the expected output.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 49 of 64
:
Microservices using ASP.NET Core:

Microservices architecture is an approach to designing and building software systems as a


collection of small, independent services that communicate with each other through well-defined
APIs. ASP.NET Core is a popular framework for building web applications, including microservices.
Here are the key steps and considerations for developing microservices using ASP.NET Core:

Define Your Microservices:

Identify the different components of your application that can be split into separate

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 50 of 64
:
microservices. Each microservice should have a specific and well-defined responsibility.

Set Up the Development Environment:

Install .NET Core SDK: Ensure you have the .NET Core SDK installed on your development
machine.
Choose an Integrated Development Environment (IDE) like Visual Studio, Visual Studio
Code, or JetBrains Rider.

Create Individual Microservices:

Create a new ASP.NET Core project for each microservice using the dotnet new command
or your IDE.
Define the API endpoints and business logic for each microservice within its own project.

Design APIs:

Define clear and consistent API contracts for your microservices. This includes specifying the
data format (e.g., JSON) and the HTTP methods (GET, POST, PUT, DELETE) each service
will support.
Use RESTful principles or consider alternatives like GraphQL for defining APIs.

Implement Communication:

Microservices need to communicate with each other. Common approaches include


HTTP/HTTPS, gRPC, and message queues like RabbitMQ or Apache Kafka.
Use HTTP clients or libraries like HttpClient in ASP.NET Core for making HTTP requests
between microservices.

Containerize Microservices:

Containerization, often using Docker, is a common practice for deploying microservices.


Container images can be easily deployed and scaled using container orchestration platforms
like Kubernetes.
Create a Dockerfile for each microservice to package it as a container.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 51 of 64
:
Deployment and Orchestration:

Deploy your containerized microservices to a container orchestration platform, such as


Kubernetes, Docker Swarm, or Azure Kubernetes Service (AKS).
Use environment variables or configuration files to manage service-specific settings.

Load Balancing:

Implement load balancing to distribute traffic evenly across multiple instances of the same
microservice to improve scalability and fault tolerance.

Service Discovery:

Use service discovery mechanisms like Consul, Eureka, or Kubernetes service discovery to
locate and connect to other microservices dynamically.

Logging and Monitoring:

Implement logging and monitoring for each microservice to gain insights into its behavior and
performance. Tools like Prometheus, Grafana, and ELK stack can be helpful.

Security:

Implement security measures like authentication and authorization for your microservices.
Use OAuth, JWT, or API keys, depending on your requirements.
Secure communication between services using HTTPS or other secure protocols.

Testing:

Write unit tests, integration tests, and end-to-end tests for each microservice to ensure their
reliability and functionality.
Consider tools like xUnit, NUnit, and Selenium for testing.

CI/CD:

Set up Continuous Integration/Continuous Deployment (CI/CD) pipelines to automate the


building, testing, and deployment of your microservices.

https://dotnettutorials.net/lesson/microservices-using-asp-net-core/ 05/05/25, 7 39 PM
Page 52 of 64
:

You might also like