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.
- Understanding Microservices using ASP.NET Core
- What are Microservices?
- Need for a Microservice
- Advantages of Microservices
- Difference between Monolith Architecture and Microservice
- Microservices Architecture
- Understanding API Gateway (Ocelot Gateway with example)
- Features of API Gateway
- Creating Microservices in ASP.NET core
- Creating an API Gateway in ASP.NET Core
- Creating API Gateway Project using Ocelot
- Configure API Gateway and Integrate Microservices
- Configuring Ocelot Routes in ASP.NET Core
- Testing Microservices
- Testing Microservice through API Gateway
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.
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 aligning them to work without downtimes because we maintain them in different servers and have to deal with the data and databases they use for transactions.
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 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.
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.
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 development of User Interface, Business Functional Components, and Database Logic. | Multiple Services are developed with a single purpose each. |
Single Database due to complex coupled development | Dedicated Database for each microservice due to modularity. |
Single programming Language dependency for the Backend (Business logic) | Ability to choose multiple technologies/languages for each microservice. |
The solution has to be deployed into a single Server. Physical Separation of deployment and maintenance is complex. | Each of the Microservices can be deployed anywhere on the web with ease. |
Different business functionalities, technically called modules or components, will be tightly coupled to the application itself. | Loosely Coupled Architecture because of the modular approach. |
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.
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)
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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; } } }
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.
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.
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.
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; 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.
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.
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.
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 { [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.
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.
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.
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 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.
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.
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.
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; 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.ContentRootPath) .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; 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(); 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.
- DownstreamPathTemplate is the path of the actual endpoint in the Microservice to which the API Gateway redirects the incoming request from the client.
- DownstreamScheme is the scheme used by Microservice, which is HTTPS.
- DownstreamHostAndPorts defines the location of the Microservice, where we will add the host details and port number details.
- UpstreamPathTemplate is the path directed to the Ocelot API Gateway exposed to send requests from the client.
- 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 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"] } ] }
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.
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.
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.
And also, for /apigateway/AttendanceService in API Gateway, you will get results from Student Attendance Microservice as expected, as shown in the below image.
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://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.
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 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.
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 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.
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.
Monitoring and Maintenance:
- Continuously monitor your microservices in production and use metrics and logs to identify and address issues.
Maintain and update your microservices to add features, fix bugs, and ensure security.
Microservices architecture offers flexibility and scalability but also introduces complexity. Proper design, communication, and orchestration are crucial for the success of a microservices-based application built using ASP.NET Core.
Here, in this article, I try to explain Microservices using ASP.NET Core. And I hope you enjoy these Microservices using the ASP.NET Core article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
Dear Sir,
It is requested, Kindly share the rest of the articles of asp.net core microservice.
Thanks
Its greate article to learn Microservices. Thank you.
I would like to request you to write Articles on Web-Api UnitTest in Asp.Net Core using Multiple Layers (UnitTest of Business Layer, Data Access Layer,Controllers etc… Other Layers)
It was great article. Thanks for this.
🙂
This very nice article to understand microservice architecture and how to write code in microservices. Thank you sir. Please make a also article on how deploy microservice on cloud with example of container or kubernative.
Easy to understand, explained step by step. Thank you
You have to remove the weatherforecast controller references in the launchsettings.json files and update launchURL to api/[Controller] name, then only the code works.
Easy to understand, explained step by step. Thank you
very useful. Thanks
thanks , its very helpful
Great article!!! I wan to know how one microservice can communicate with another microservice? as per the example, how attendance service can get some detail from admission service?
That’s Awesome than we expected. Hello Everybody from the Uzbekistan.