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

Microservices Implementation With Ocelot Gateway Using .NET Core 6 API and Angular 14

This document outlines the implementation of microservices using Ocelot API Gateway with .NET Core 6 and Angular 14. It provides a step-by-step guide on creating two microservices, ProductAPI and UserAPI, detailing the necessary prerequisites, architecture differences between monolithic and microservices, and the configuration of the Ocelot API Gateway. The document includes code snippets for setting up the services, controllers, and database context for both APIs.

Uploaded by

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

Microservices Implementation With Ocelot Gateway Using .NET Core 6 API and Angular 14

This document outlines the implementation of microservices using Ocelot API Gateway with .NET Core 6 and Angular 14. It provides a step-by-step guide on creating two microservices, ProductAPI and UserAPI, detailing the necessary prerequisites, architecture differences between monolithic and microservices, and the configuration of the Ocelot API Gateway. The document includes code snippets for setting up the services, controllers, and database context for both APIs.

Uploaded by

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

16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .

NET Core 6 API And Angular 14

Microservices Implementation With Ocelot Gateway


Using .NET
Ads by
Core 6 API And Angular 14
Jaydeep Patil Aug 07, 2022 40.4k 9 10
Stop seeing this ad

Why this ad?


OcelotGatewayExample.zip

In this article, we are going to create two microservices using Ocelot API Gateway using Client
Application, which is designed in Angular 14.

Agenda
Introduction of Microservice
Introduction of Ocelot API Gateway
Step-by-step implementation of microservices
ImplementationAds by API Gateway
of Ocelot
Client Application
Stopusing Angular
seeing this ad14

Prerequisites: Why this ad?

Understanding of .NET Core API, C#, and Angular


Visual Studio 2022
VS Code
Node Js
Angular 14
.NET Core 6 SDK

Introduction of Microservice
There are two types of architecture for design applications: the first is monolithic, and the second
one is microservices.

1. Monolithic Architecture
In a Monolithic Application, all components are tightly coupled to each other and run using a
single process.
It’s very difficult to make some changes in the future when monolithic architecture is used,
because the components of the application will be tightly coupled to each other. When trying to
modify or introduce new things into the existing component, this may impact all applications.
Suppose we have an E-commerce application and in that application, we used multiple
components, like Login, Posts, and News Feed. In that case, when we introduce or change
something in one of the components, it will impact the application because the application is
tightly coupled and interconnected to each other using a single service.
If we have deployed this type of application on the cloud, and in the future we need to add
something into the Posts Component, then we will be required to stop the whole application.
This will impact performance and delivery services' efficiency. Also, it’s difficult to manage.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 1/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

2. Microservice Architecture
In the Microservice Architecture, we create application components that will work independently,
without being tightly coupled to each other, in their own environments.
Also, we can easily communicate with each other with the help of API Gateways and other such
programs.
So, basically, when we use microservices, they will run their own environment, and they will not
impact one another when we change something in one of the services.
Also, this is easy to manage while the application is in a development phase. Each developer
will work independently on each service, and because of that, it is easy to manage and
integrate components.

Introduction of Ocelot API Gateway


Ocelot is the API Gateway for the .NET Platform and which is work as the entry point of our
application when we use microservice architecture.
The following diagram is from Microsoft Technical Documentation.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 2/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

API gateway is present between the client and microservices and acts as middleware for
communication between different microservices as shown in the above diagram.

Step-by-step implementation of microservices


Let’s start.

Step 1

Create a Blank Empty solution using a visual studio.

Step 2

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 3/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

Configure your project.

Step 3

Project Structure:

Step 4

Create a new folder inside the solution and name it Microservices. Next, create ProductAPI and
UserAPI projects inside that.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 4/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 5

Configure ProductAPI project.

Step 6

Provide additional information related to project.

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 7

Next, create the UserAPI project inside the Microservices folder and follow the same steps as we
used to create ProductAPI.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 5/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 8

Create an Ocelot API Gateway project outside the Microservices folder.

Let’s start the implementation of ProductAPI


Project Structure

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 1

Install the following NuGet packages.

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 2

Create Product Class inside the Model folder.

1 namespace ProductAPI.Models
2 {
3 public class Product
4 {
5 public int ProductId { get; set; }
6 public string ProductName { get; set; }
7 public string ProductDescription { get; set; }
8 public int ProductPrice { get; set; }
9 public int ProductStock { get; set; }
10 }
11 }

Step 3

Next, Create DBContextClass inside the Data folder.

using Microsoft.EntityFrameworkCore;
using ProductAPI.Models;

namespace ProductAPI.Data
{
public class DbContextClass : DbContext
{
protected readonly IConfiguration Configuration;

public DbContextClass(IConfiguration configuration)


{
Configuration = configuration;
}
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 6/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
14 protected override void OnConfiguring(DbContextOptionsBuilder opt
15 {
16 options.UseSqlServer(Configuration.GetConnectionString("Defau
17 }
18
19 public DbSet<Product> Products { get; set; }
20 }
21 }

Step 4

After that, create IProductService and ProductService inside the services folder.

IProductService

1 using ProductAPI.Models;
2
3 namespace ProductAPI.Services
4 {
5 public interface IProductService
6 {
7 public IEnumerable<Product> GetProductList();
8 public Product GetProductById(int id);
9 public Product AddProduct(Product product);
10 public Product UpdateProduct(Product product);
11 public bool DeleteProduct(int Id);
12 }
13 }

ProductService

using ProductAPI.Data;
using ProductAPI.Models;

namespace ProductAPI.Services
{
public class ProductService : IProductService
{
private readonly DbContextClass _dbContext;

public ProductService(DbContextClass dbContext)


{
_dbContext = dbContext;
}
public IEnumerable<Product> GetProductList()

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 7/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

16 {
17 return _dbContext.Products.ToList();
18 }
19 public Product GetProductById(int id)
20 {
21 return _dbContext.Products.Where(x => x.ProductId == id).Firs
22 }
23
24 public Product AddProduct(Product product)
25 {
26 var result = _dbContext.Products.Add(product);
27 _dbContext.SaveChanges();
28 return result.Entity;
29 }
30
31 public Product UpdateProduct(Product product)
32 {
33 var result = _dbContext.Products.Update(product);
34 _dbContext.SaveChanges();
35 return result.Entity;
36 }
37 public bool DeleteProduct(int Id)
38 {
39 var filteredData = _dbContext.Products.Where(x => x.ProductId
40 var result = _dbContext.Remove(filteredData);
41 _dbContext.SaveChanges();
42 return result != null ? true : false;
43 }
44 }
}

Step 5

Configure the connection string inside the appsetting.json file.

(Note: I used the same database for demo purposes in both Product and User
Microservice but in a real-time scenario you can use the separate database for each
microservice as per microservice guidelines and protocols.)

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 8/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
7 },
8 "AllowedHosts": "*",
9 "ConnectionStrings": {
10 "DefaultConnection": "Data Source=DESKTOP;Initial Catalog=OcelotGatew
11 }
12 }

Step 6

Later on, configure a few services inside Program.cs class.

1 using ProductAPI.Data;
2 using ProductAPI.Services;
3 var builder = WebApplication.CreateBuilder(args);
4 // Add services to the container.
5 builder.Services.AddScoped < IProductService, ProductService > ();
6 builder.Services.AddDbContext < DbContextClass > ();
7 builder.Services.AddControllers();
8 builder.Services.AddEndpointsApiExplorer();
9 builder.Services.AddSwaggerGen();
10 var app = builder.Build();
11 // Configure the HTTP request pipeline.
12 if (app.Environment.IsDevelopment()) {
13 app.UseSwagger();
14 app.UseSwaggerUI();
15 }
16 app.UseHttpsRedirection();
17 app.UseAuthorization();
18 app.MapControllers();
19 app.Run();

Step 7

Next, Create a ProductController.cs.

1 using Microsoft.AspNetCore.Mvc;
2 using ProductAPI.Models;
3 using ProductAPI.Services;
4 namespace ProductAPI.Controllers {
5 [Route("api/[controller]")]
6 [ApiController]
7 public class ProductController: ControllerBase {
8 private readonly IProductService productService;
9 public ProductController(IProductService _productService) {
10 productService = _productService;
11
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 9/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

12 }
13 [HttpGet]
14 public IEnumerable < Product > ProductList() {
15 var productList = productService.GetProductList();
16 return productList;
17 }
18 [HttpGet("{id}")]
19 public Product GetProductById(int id) {
20 return productService.GetProductById(id);
21 }
22 [HttpPost]
23 public Product AddProduct(Product product) {
24 return productService.AddProduct(product);
25 }
26 [HttpPut]
27 public Product UpdateProduct(Product product) {
28 return productService.UpdateProduct(product);
29 }
30 [HttpDelete("{id}")]
31 public bool DeleteProduct(int id) {
32 return productService.DeleteProduct(id);
33 }
34 }
}

Step 8

Finally, execute the following command in the package manager console to create migration and
create the database.

1 add-migration "Initial"
2 update-database

Implementation of UserAPI service


Project Structure:

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 1

Install the following NuGet packages:

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 2

Create a User Class inside the Model folder.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 10/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

1 namespace UserAPI.Models
2 {
3 public class User
4 {
5 public int UserId { get; set; }
6 public string UserName { get; set; }
7 public string Address { get; set; }
8 }
9 }

Step 3

Next, Create DBContextClass inside the Data folder.

1 using Microsoft.EntityFrameworkCore;
2 using UserAPI.Models;
3
4 namespace UserAPI.Data
5 {
6 public class DbContextClass : DbContext
7 {
8 protected readonly IConfiguration Configuration;
9
10 public DbContextClass(IConfiguration configuration)
11 {
12 Configuration = configuration;
13 }
14 protected override void OnConfiguring(DbContextOptionsBuilder opt
15 {
16 options.UseSqlServer(Configuration.GetConnectionString("Defau
17 }
18
19 public DbSet<User> Users { get; set; }
20 }
21 }

Step 4

After that, create IUserService and UserService inside the services folder.

IUserService

1 using UserAPI.Models;
2
3 namespace UserAPI.Services
4 {
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 11/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
5 public interface IUserService
6 {
7 public IEnumerable<User> GetUserList();
8 public User GetUserById(int id);
9 public User AddUser(User product);
10 public User UpdateUser(User product);
11 public bool DeleteUser(int Id);
12 }
13 }

UserService

using UserAPI.Data;
using UserAPI.Models;

namespace UserAPI.Services
{
public class UserService : IUserService
{
private readonly DbContextClass _dbContext;

public UserService(DbContextClass dbContext)


{
_dbContext = dbContext;
}

public User AddUser(User product)


{
var result = _dbContext.Users.Add(product);
_dbContext.SaveChanges();
return result.Entity;
}

public bool DeleteUser(int Id)


{
var filteredData = _dbContext.Users.Where(x => x.UserId == Id
var result = _dbContext.Remove(filteredData);
_dbContext.SaveChanges();
return result != null ? true : false;
}

public User GetUserById(int id)


{
return _dbContext.Users.Where(x => x.UserId == id).FirstOrDef
}

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 12/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
34
35
36 public IEnumerable<User> GetUserList()
37 {
38 return _dbContext.Users.ToList();
39 }
40
public User UpdateUser(User product)
41
{
42
var result = _dbContext.Users.Update(product);
43
_dbContext.SaveChanges();
44
return result.Entity;
45
}
46
47 }
}

Step 5

Configure the connection string inside the appsetting.json file.

(Note: I used the same database for demo purposes in both Product and User
Microservice but in a real-time scenario you can use the separate database for each
microservice as per microservice guidelines and protocols.)

1 {
2 "Logging": {
3 "LogLevel": {
4 "Default": "Information",
5 "Microsoft.AspNetCore": "Warning"
6 }
7 },
8 "AllowedHosts": "*",
9 "ConnectionStrings": {
10 "DefaultConnection": "Data Source=DESKTOP;Initial Catalog=OcelotGatew
11 }
12 }

Step 6

Later on, configure a few services inside Program.cs class.

using UserAPI.Data;
using UserAPI.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped < IUserService, UserService > ();
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 13/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
6 builder.Services.AddDbContext < DbContextClass > ();
7 builder.Services.AddControllers();
8 // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetc
9 builder.Services.AddEndpointsApiExplorer();
10 builder.Services.AddSwaggerGen();
11 var app = builder.Build();
12 // Configure the HTTP request pipeline.
13 if (app.Environment.IsDevelopment()) {
14 app.UseSwagger();
15 app.UseSwaggerUI();
16 }
17 app.UseHttpsRedirection();
18 app.UseAuthorization();
19 app.MapControllers();
20 app.Run();

Step 7

Next, Create a UserController.cs.

1 using Microsoft.AspNetCore.Mvc;
2 using UserAPI.Models;
3 using UserAPI.Services;
4 namespace UserAPI.Controllers {
5 [Route("api/[controller]")]
6 [ApiController]
7 public class UserController: ControllerBase {
8 private readonly IUserService userService;
9 public UserController(IUserService _userService) {
10 userService = _userService;
11 }
12 [HttpGet]
13 public IEnumerable < User > UserList() {
14 var userList = userService.GetUserList();
15 return userList;
16 }
17 [HttpGet("{id}")]
18 public User GetUserById(int Id) {
19 return userService.GetUserById(Id);
20 }
21 [HttpPost]
22 public User AddUser(User user) {
23 return userService.AddUser(user);
24 }
25
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 14/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

26 [HttpPut]
27 public User UpdateUser(User user) {
28 return userService.UpdateUser(user);
29 }
30 [HttpDelete("{id}")]
31 public bool DeleteUser(int id) {
32 return userService.DeleteUser(id);
33 }
34 }
}

Step 8

Finally, execute the following command in the package manager console to create migration, and
create the database.

1 add-migration "Initial"
2 update-database

Implementation of Ocelot API Gateway


Step 1

Install Ocelot NuGet Package.

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 2

Project Structure:

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 3

Create an ocelot.json file for routing.

1 {
2 "GlobalConfiguration": {
3 "BaseUrl": "https://localhost:7283"
4 },
5 "Routes": [
6 {
7 "UpstreamPathTemplate": "/gateway/product",
8 "UpstreamHttpMethod": [ "Get" ],
9 "DownstreamPathTemplate": "/api/product",
10 "DownstreamScheme": "https",
11 "DownstreamHostAndPorts": [
12 {
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 15/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
13 "Host": "localhost",
14 "Port": 7233
15 }
16 ]
17 },
18 {
19 "UpstreamPathTemplate": "/gateway/product/{id}",
20 "UpstreamHttpMethod": [ "Get", "Delete" ],
21 "DownstreamPathTemplate": "/api/product/{id}",
22 "DownstreamScheme": "https",
23 "DownstreamHostAndPorts": [
24 {
25 "Host": "localhost",
26 "Port": 7233
27 }
28 ]
29 },
30 {
31 "UpstreamPathTemplate": "/gateway/product",
32 "UpstreamHttpMethod": [ "Post", "Put" ],
33 "DownstreamPathTemplate": "/api/product",
34 "DownstreamScheme": "https",
35 "DownstreamHostAndPorts": [
36 {
37 "Host": "localhost",
38 "Port": 7233
39 }
40 ]
41 },
42 {
43 "UpstreamPathTemplate": "/gateway/user",
44 "UpstreamHttpMethod": [ "Get" ],
45 "DownstreamPathTemplate": "/api/user",
46 "DownstreamScheme": "https",
47 "DownstreamHostAndPorts": [
48 {
49 "Host": "localhost",
50 "Port": 7285
51 }
52 ]
53 },
54 {
55 "UpstreamPathTemplate": "/gateway/user/{id}",
56 "UpstreamHttpMethod": [ "Get", "Delete" ],
57 "DownstreamPathTemplate": "/api/user/{id}",
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 16/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
58 "DownstreamScheme": "https",
59 "DownstreamHostAndPorts": [
60 {
61 "Host": "localhost",
62 "Port": 7285
63 }
64 ]
65 },
66 {
67 "UpstreamPathTemplate": "/gateway/user",
68 "UpstreamHttpMethod": [ "Post", "Put" ],
69 "DownstreamPathTemplate": "/api/user",
70 "DownstreamScheme": "https",
71 "DownstreamHostAndPorts": [
72 {
73 "Host": "localhost",
74 "Port": 7285
75 }
76 ]
77 }
78 ]
79 }

The Ocelot file has two sections: one is Global Configuration, which acts as an entry point of
our application; and the other is Routes, which is used to define routes of our microservices.
UpstreamPathTemplate is used to receive client requests and redirects them to the particular
microservice.
UpstreamHttpMethod is used to define HTTP attributes, which helps to the gateway to getting
the type of request.
DownstreamTemplatePath is the microservice endpoint that takes the request from
UpstreamPathTemplate.
DownstreamScheme defines the scheme of a request.
DownstreamHostAndPorts defines the hostname and port number of microservices that are
present inside the lauchSetting.json file.

Step 4

Configure the ocelot.json file inside Program.cs class and register services related to that. Then,
apply CORS policy for client communication, which we are going to create using Angular.

using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options => {
options.AddPolicy("CORSPolicy", builder => builder.AllowAnyMethod().A

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 17/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
7
});
8
builder.Services.AddControllers();
9
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetc
10
builder.Services.AddEndpointsApiExplorer();
11
builder.Services.AddSwaggerGen();
12
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadO
13
builder.Services.AddOcelot(builder.Configuration);
14
var app = builder.Build();
15
// Configure the HTTP request pipeline.
16
if (app.Environment.IsDevelopment()) {
17
app.UseSwagger();
18
app.UseSwaggerUI();
19
}
20
app.UseCors("CORSPolicy");
21
app.UseHttpsRedirection();
22
app.UseAuthorization();
23
app.MapControllers();
24
await app.UseOcelot();
25
app.Run();

Step 5

Right-click on the solution and open the property. Then, apply to start on all three projects that we
have created.

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 6

Run the project.

This is all about backend application using microservices, let’s start the client application.

Client Application using Angular 14


Step 1

Create a new angular project.

1 ng new ClientApplication

Step 2

We use bootstrap in this application. So, use the following command to install bootstrap.

1 npm install bootstrap

Next, add the bootstrap script inside the angular.json file inside the scripts and styles section.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 18/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

1 "styles": [
2 "src/styles.css",
3 "./node_modules/bootstrap/dist/css/bootstrap.min.css"
4 ],
5 "scripts": [
6 "./node_modules/bootstrap/dist/js/bootstrap.min.js"
7 ]

Step 3

Install Toaster module for pop-up and notification.

1 npm install ngx-toastr –save

Then, add the toaster in the styles section inside the angular.json file.

1 "styles": [
2 "src/styles.css",
3 "node_modules/ngx-toastr/toastr.css",
4 "./node_modules/bootstrap/dist/css/bootstrap.min.css"
5 ],
6 "scripts": [
7 "./node_modules/bootstrap/dist/js/bootstrap.min.js"
8 ]

Step 4

Create Product and User class inside the Model folder.

Product.ts

1 export class Product {


2 productId: any;
3 productName?: string;
4 productPrice?: number;
5 productDescription?: string;
6 productStock?: number;
7 }

User.ts

1 export class User {


2 userId: any;
3 userName?: string;
4 address?: string;
5 }

Step 5

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 19/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

Next, create three components using the following command:

1 ng g c homepage
2
3 ng g c products
4
5 ng g c users

Step 6

After that, create a Product angular service.

1 ng g s products

1 import { HttpClient, HttpHeaders } from '@angular/common/http';


2 import { Injectable } from '@angular/core';
3 import { Observable } from 'rxjs';
4 import { Product } from '../Models/Product';
5 import configurl from '../../assets/config/config.json'
6 @Injectable({
7 providedIn: 'root'
8 })
9 export class ProductsService {
10
11 url = configurl.apiServer.url + '/product';
12 constructor(private http: HttpClient) { }
13 getProductList(): Observable<Product[]> {
14 return this.http.get<Product[]>(this.url);
15 }
16 postProductData(productData: Product): Observable<Product> {
17 const httpHeaders = { headers:new HttpHeaders({'Content-Type': 'appli
18 return this.http.post<Product>(this.url, productData, httpHeaders);
19 }
20 updateProduct(product: Product): Observable<Product> {
21 const httpHeaders = { headers:new HttpHeaders({'Content-Type': 'appli
22 return this.http.put<Product>(this.url, product, httpHeaders);
23 }
24 deleteProductById(id: number): Observable<number> {
25 return this.http.delete<number>(this.url + '/' + id);
26 }
27 getProductDetailsById(id: string): Observable<Product> {
28 return this.http.get<Product>(this.url + '/' + id);
29 }
30 }

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 20/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

Step 7

Next, create Users angular service.

1 ng g s users

1 import { Injectable } from '@angular/core';


2 import { Observable } from 'rxjs';
3 import { User } from '../Models/User';
4 import configurl from '../../assets/config/config.json'
5 import { HttpClient, HttpHeaders } from '@angular/common/http';
6
7 @Injectable({
8 providedIn: 'root'
9 })
10 export class UsersService {
11
12 url = configurl.apiServer.url + '/user';
13 constructor(private http: HttpClient) { }
14 getUserList(): Observable<User[]> {
15 return this.http.get<User[]>(this.url);
16 }
17 postUserData(userData: User): Observable<User> {
18 const httpHeaders = { headers:new HttpHeaders({'Content-Type': 'appli
19 return this.http.post<User>(this.url, userData, httpHeaders);
20 }
21 updateUser(user: User): Observable<User> {
22 const httpHeaders = { headers:new HttpHeaders({'Content-Type': 'appli
23 return this.http.put<User>(this.url, user, httpHeaders);
24 }
25 deleteUserById(id: number): Observable<number> {
26 return this.http.delete<number>(this.url + '/' + id);
27 }
28 getUserDetailsById(id: string): Observable<User> {
29 return this.http.get<User>(this.url + '/' + id);
30 }
31 }

Step 8

Create app-routing.module.ts to define the routes of the angular component.

1 import { NgModule } from '@angular/core';


2 import { RouterModule, Routes } from '@angular/router';
3 import { HomepageComponent } from './homepage/homepage.component';
4
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 21/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

5 import { ProductsComponent } from './products/products.component';


6 import { UsersComponent } from './users/users.component';
7
8 const routes: Routes = [
9 { path: '', component: HomepageComponent },
10 { path: 'products', component: ProductsComponent },
11 { path: 'users', component: UsersComponent }
12
13 ];
14
15 @NgModule({
16 imports: [RouterModule.forRoot(routes)],
17 exports: [RouterModule]
18 })
export class AppRoutingModule { }

Step 9

Configure and define all modules in the app.module.ts.

1 import { NgModule } from '@angular/core';


2 import { BrowserModule } from '@angular/platform-browser';
3
4 import { AppRoutingModule } from './app-routing.module';
5 import { AppComponent } from './app.component';
6 import { HttpClientModule } from '@angular/common/http';
7 import { ProductsComponent } from './products/products.component';
8 import { UsersComponent } from './users/users.component';
9 import { ToastrModule } from 'ngx-toastr';
10 import { FormsModule, ReactiveFormsModule } from '@angular/forms';
11 import { HomepageComponent } from './homepage/homepage.component';
12
13 @NgModule({
14 declarations: [
15 AppComponent,
16 ProductsComponent,
17 UsersComponent,
18 HomepageComponent
19 ],
20 imports: [
21 BrowserModule,
22 AppRoutingModule,
23 HttpClientModule,
24 ToastrModule,
25 HttpClientModule,
26 FormsModule,
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 22/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

27 ReactiveFormsModule,
28 ToastrModule.forRoot(),
29 ],
30 providers: [],
31 bootstrap: [AppComponent]
32 })
33 export class AppModule { }

Step 10

Create a config folder inside the assets folder, and then create a config.json file to define the
backend server API URL.

1 {
2 "apiServer": {
3 "url": "https://localhost:7283/gateway",
4 "version": "v1"
5 }
6 }

Step 11

App Component:

app.component.ts

1 import { Component } from '@angular/core';


2
3 @Component({
4 selector: 'app-root',
5 templateUrl: './app.component.html',
6 styleUrls: ['./app.component.css']
7 })
8 export class AppComponent {
9
10 title = 'ProductWebAPP';
11 }

app.component.html

1 <router-outlet></router-outlet>

Homepage Component

homepage.component.ts

1 import { Component } from '@angular/core';


2
3
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 23/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

4 @Component({
5 selector: 'app-homepage',
6 templateUrl: './homepage.component.html',
7 styleUrls: ['./homepage.component.css']
8 })
9 export class HomepageComponent {
10
11 title: string ="Ocelot Gateway Microservices Demo";
12
}

homepage.component.html

1 <nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">


2 <a class="navbar-brand" href="#">{{title}}</a>
3 <button class="navbar-toggler" type="button" data-toggle="collapse" d
4 <span class="navbar-toggler-icon"></span>
5 </button>
6 <div class="collapse navbar-collapse" id="navbarText">
7 <ul class="navbar-nav mr-auto">
8 <li class="nav-item">
9 <a class="nav-link" routerLink="/products">Products</a>
10 </li>
11 <li class="nav-item">
12 <a class="nav-link" routerLink="/users">Users</a>
13 </li>
14 </ul>
15 </div>
16 </nav>
17 <h1>Welcome To Programming World!</h1>

Product Component

product.component.ts

import { Component, OnInit } from '@angular/core';


import { Observable } from 'rxjs';
import { ProductsService } from '../products/products.service';
import { Product } from '../Models/Product';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 24/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
ProductList ? : Observable < Product[] > ;
ProductList1 ? : Observable < Product[] > ;
productForm: any;
productId = 0;
constructor(private formbulider: FormBuilder, private productService:
ngOnInit() {
this.productForm = this.formbulider.group({
productName: ['', [Validators.required]],
productPrice: ['', [Validators.required]],
productDescription: ['', [Validators.required]],
productStock: ['', [Validators.required]]
});
this.getProductList();
}
getProductList() {
this.ProductList1 = this.productService.getProductList();
this.ProductList = this.ProductList1;
}
PostProduct(product: Product) {
const product_Master = this.productForm.value;
this.productService.postProductData(product_Master).subscribe(
() => {
this.getProductList();
this.productForm.reset();
this.toastr.success('Data Saved Successfully');
});
}
ProductDetailsToEdit(id: string) {
this.productService.getProductDetailsById(id).subscribe(productRe
this.productId = productResult.productId;
this.productForm.controls['productName'].setValue(productResu
this.productForm.controls['productPrice'].setValue(productRes
this.productForm.controls['productDescription'].setValue(prod
this.productForm.controls['productStock'].setValue(productRes
});
}
UpdateProduct(product: Product) {
product.productId = this.productId;
const product_Master = this.productForm.value;
this.productService.updateProduct(product_Master).subscribe(() =>
this.toastr.success('Data Updated Successfully');
this.productForm.reset();
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 25/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

57 this.getProductList();
58 });
59 }
60 DeleteProduct(id: number) {
61 if (confirm('Do you want to delete this product?')) {
62 this.productService.deleteProductById(id).subscribe(() => {
63 this.toastr.success('Data Deleted Successfully');
64 this.getProductList();
65 });
66 }
67 }
68 Clear(product: Product) {
69 this.productForm.reset();
70 }
}

prouct.component.html

<nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">


<a class="navbar-brand" href="#">Product Application</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" d
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" routerLink="/">Home</a>
</li>
<li class="nav-item active">
<a class="nav-link" routerLink="/products">Products</a>
</li>
<li class="nav-item active">
<a class="nav-link" routerLink="/users">Users</a>
</li>
</ul>
</div>
</nav>

<form class="form-horizontal" [formGroup]="productForm">


<h1 style="text-align: center;">Welcome to Angular 14 CRUD with .NE
<div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Name:</la
<div class="col-sm-10">

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 26/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

<input type="text" class="form-control" id="txtProductName" for


placeholder="Name of Product">
</div>
</div>
<br />
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Descripti
<div class="col-sm-10">
<input type="text" class="form-control" id="txtProductDescripti
placeholder="Product Description">
</div>
</div>
<br />
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Cost:</la
<div class="col-sm-10">
<input type="text" class="form-control" id="txtProductPrice" fo
</div>
</div>
<br />
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Stock Ava
<div class="col-sm-10">
<input type="text" class="form-control" id="txtStock" formContr
</div>
</div>
<br />
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-sm">
<button type="submit" class="btn btn-primary" (click)="Post
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" (click)="Upda
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" (click)="Clea
</div>
</div>
</div>
<br />
</div>
<div>
<div class="alert alert-success" style="text-align: center;"><b>P
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 27/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

73 <div class="table-responsive" style="text-align: center;">


74 <table class="table table-striped">
75 <thead>
76 <tr>
77 <th scope="col">#</th>
78 <th scope="col">Product Name</th>
79 <th scope="col">Description</th>
80 <th scope="col">Cost</th>
81 <th scope="col">Stock</th>
82 <th scope="col">Action</th>
83 </tr>
84 </thead>
85 <tbody>
86 <tr *ngFor="let prd of ProductList | async; index as i">
87 <th scope="row">{{ i + 1 }}</th>
88 <td>{{prd.productName}}</td>
89 <td>{{prd.productDescription}}</td>
90 <td>{{prd.productPrice}}</td>
91 <td>{{prd.productStock}}</td>
92 <td><button type="button" class="btn1" matTooltip="Click Ed
93 |
94 <button type="button" class="btn1" matTooltip="Click Dele
95 </td>
96 </tr>
97 </tbody>
98 </table>
99 </div>
100 </div>
101 </div>
</form>

User Component

user.component.ts

1 import { Component, OnInit } from '@angular/core';


2 import { FormBuilder, Validators } from '@angular/forms';
3 import { Router } from '@angular/router';
4 import { ToastrService } from 'ngx-toastr';
5 import { Observable } from 'rxjs';
6 import { User } from '../Models/User';
7 import { UsersService } from './users.service';
8
9 @Component({
10 selector: 'app-users',
11
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 28/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

12 templateUrl: './users.component.html',
13 styleUrls: ['./users.component.css']
14 })
15 export class UsersComponent implements OnInit {
16
17 UserList?: Observable<User[]>;
18 UserList1?: Observable<User[]>;
19 userForm: any;
20 userId = 0;
21
22 constructor(private formbulider: FormBuilder,
23 private userService: UsersService,private router: Router,
24 private toastr: ToastrService) { }
25
26 ngOnInit() {
27 this.userForm = this.formbulider.group({
28 userName: ['', [Validators.required]],
29 address: ['', [Validators.required]]
30 });
31 this.getUserList();
32 }
33 getUserList() {
34 this.UserList1 = this.userService.getUserList();
35 this.UserList = this.UserList1;
36 }
37 PostUser(user: User) {
38 const user_Master = this.userForm.value;
39 this.userService.postUserData(user_Master).subscribe(
40 () => {
41 this.getUserList();
42 this.userForm.reset();
43 this.toastr.success('Data Saved Successfully');
44 }
45 );
46 }
47 UserDetailsToEdit(id: string) {
48 this.userService.getUserDetailsById(id).subscribe(userResult => {
49 this.userId = userResult.userId;
50 this.userForm.controls['userName'].setValue(userResult.userName);
51 this.userForm.controls['address'].setValue(userResult.address);
52 });
53 }
54 UpdateUser(user: User) {
55 user.userId = this.userId;
56 const user_Master = this.userForm.value;
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 29/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

57 this.userService.updateUser(user_Master).subscribe(() => {
58 this.toastr.success('Data Updated Successfully');
59 this.userForm.reset();
60 this.getUserList();
61 });
62 }
63
64 DeleteUser(id: number) {
65 if (confirm('Do you want to delete this user?')) {
66 this.userService.deleteUserById(id).subscribe(() => {
67 this.toastr.success('Data Deleted Successfully');
68 this.getUserList();
69 });
70 }
71 }
72
73 Clear(user: User){
74 this.userForm.reset();
75 }
76
}

user.component.html

<nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">


<a class="navbar-brand" href="#">Users Application</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" d
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" routerLink="/">Home</a>
</li>
<li class="nav-item active">
<a class="nav-link" routerLink="/products">Products</a>
</li>
<li class="nav-item active">
<a class="nav-link" routerLink="/users">Users</a>
</li>
</ul>
</div>
</nav>

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 30/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

<form class="form-horizontal" [formGroup]="userForm">


<h1 style="text-align: center;">Welcome to Angular 14 CRUD with .NE
<div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">User Name:</label
<div class="col-sm-10">
<input type="text" class="form-control" id="txtUserName" formCo
placeholder="Name of User">
</div>
</div>
<br />
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Address :</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="txtUserDescription"
placeholder="User Address">
</div>
</div>
<br />
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-sm">
<button type="submit" class="btn btn-primary" (click)="Post
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" (click)="Upda
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" (click)="Clea
</div>
</div>
</div>
<br />
</div>
<div>
<div class="alert alert-success" style="text-align: center;"><b>U
<div class="table-responsive" style="text-align: center;">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">User Name</th>
<th scope="col">Address</th>
<th scope="col">Action</th>
https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 31/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14
66
67 </tr>
68 </thead>
69 <tbody>
70 <tr *ngFor="let user of UserList | async; index as i">
71 <th scope="row">{{ i + 1 }}</th>
72 <td>{{user.userName}}</td>
73 <td>{{user.address}}</td>
74 <td><button type="button" class="btn1" matTooltip="Click Ed
75 |
76 <button type="button" class="btn1" matTooltip="Click Dele
77 </td>
78 </tr>
79 </tbody>
80 </table>
81 </div>
82 </div>
83 </div>
</form>

Step 12

Finally, run the application

1 npm start

Homepage Component

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Product Component

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

User Component

Microservices with Ocelot Gateway Using .NET Core 6 API And Angular 14

Conclusion
In this article we discussed working of microservice architecture and ocelot API gateway using .NET
Core 6 API, and went over step-by-step implementation of client applications using Angular 14.

Happy coding!

.NET Core Angular C# JavaScript Web API

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 32/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

RECOMMENDED FREE EBOOK

.NET Interview Questions and Answer: Practical Implementation

Download Now!

SIMILAR ARTICLES

Angular 14 New Features

Microservices Async Communication Using Ocelot Gateway, RabbitMQ, Docker, And Angular 14

Build A .NET Core Microservice With Ocelot API Gateway

Microservices With Ocelot API Gateway In ASP.NET Core

SignalR Introduction And Implementation Using The .NET Core 6 Web API And Angular 14

Jaydeep Patil
C# Corner MVP | Fullstack Developer with 2.5+ yrs of experience in .NET Core API, Angular 8+,
SQL Server, Docker, Kubernetes, and Azure

110 1.9m 2

View All Comments


9

Type your comment here and press Enter Key (Minimum 10 characters)

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 33/34
16/02/2024 23:06 Microservices Implementation With Ocelot Gateway Using .NET Core 6 API And Angular 14

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners

C# Tutorials Common Interview Questions Stories Consultants Ideas Certifications Sharp TV

Web3 Universe Build with JavaScript Let's React DB Talks Jumpstart Blockchain Interviews.help
©2024 C# Corner. All contents are copyright of their authors.

https://www.c-sharpcorner.com/article/microservices-implementation-with-ocelot-gateway-using-net-core-6-api-and-angul/ 34/34

You might also like