Learn how to simplify microservices communication using YARP API Gateway in ASP.NET Core 9.0. Streamline your architecture with centralized routing and improve performance effortlessly.

In a microservices-based e-commerce application, managing multiple endpoints can be challenging for consumers. Instead of exposing separate URLs for services like Authentication, Catalog, and Order, we can simplify communication by introducing a unified API Gateway using YARP (Yet Another Reverse Proxy).

the coding blueprint Master Simplified Microservices Communication with YARP API Gateway in ASP.NET Core 9.0

Microsoft’s YARP.ReverseProxy provides a high-performance and flexible reverse proxy for ASP.NET Core applications. By consolidating all service endpoints under a single gateway, you can enhance the user experience, improve security, and centralize request routing.

Solution Folder Structure

To maintain a clean architecture, structure your solution as follows:

ecommerce-microservices/
│
├── src/
│   ├── services/
│   │   ├── AuthenticationService/
│   │   │   ├── AuthenticationService.csproj
│   │   │   ├── Controllers/
│   │   │   └── Program.cs
│   │   │
│   │   ├── CatalogService/
│   │   │   ├── CatalogService.csproj
│   │   │   ├── Controllers/
│   │   │   └── Program.cs
│   │   │
│   │   └── OrderService/
│   │       ├── OrderService.csproj
│   │       ├── Controllers/
│   │       └── Program.cs
│   │
│   └── gateway/
│       ├── ApiGateway.csproj
│       ├── appsettings.json
│       ├── Program.cs
│       └── Startup.cs
│
├── tests/
│   ├── AuthenticationService.Tests/
│   ├── CatalogService.Tests/
│   ├── OrderService.Tests/
│   └── ApiGateway.Tests/
│
├── docker-compose.yml
├── README.md
└── .gitignore

Key Components:

  1. src/services: Contains microservices (Authentication, Catalog, and Order) as individual projects.
  2. src/gateway: Contains the API Gateway project using YARP.ReverseProxy.
  3. tests: Holds unit and integration tests for each service and the API Gateway.

Configuring YARP in the API Gateway

1. Add the YARP NuGet Package

Add YARP.ReverseProxy to the API Gateway project.

cd src/gateway
dotnet add package Yarp.ReverseProxy

2. Configure YARP in appsettings.json

Define routes and clusters for each service in the API Gateway.

{
  "ReverseProxy": {
    "Routes": {
      "AuthenticationRoute": {
        "ClusterId": "AuthenticationCluster",
        "Match": {
          "Path": "/auth/{**catch-all}"
        }
      },
      "CatalogRoute": {
        "ClusterId": "CatalogCluster",
        "Match": {
          "Path": "/catalog/{**catch-all}"
        }
      },
      "OrderRoute": {
        "ClusterId": "OrderCluster",
        "Match": {
          "Path": "/order/{**catch-all}"
        }
      }
    },
    "Clusters": {
      "AuthenticationCluster": {
        "Destinations": {
          "AuthService": {
            "Address": "https://localhost:7000/"
          }
        }
      },
      "CatalogCluster": {
        "Destinations": {
          "CatalogService": {
            "Address": "https://localhost:7001/"
          }
        }
      },
      "OrderCluster": {
        "Destinations": {
          "OrderService": {
            "Address": "https://localhost:7002/"
          }
        }
      }
    }
  }
}

3. Set Up the API Gateway in Program.cs

Configure the gateway pipeline to use YARP for reverse proxying.

var builder = WebApplication.CreateBuilder(args);

// Add YARP reverse proxy services
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();

// Map the reverse proxy middleware
app.MapReverseProxy();

app.Run();

Deploying the Gateway

When the API Gateway is deployed, consumers will only interact with the gateway’s single endpoint. For example:

  • Authentication Service: https://api.yourdomain.com/auth
  • Catalog Service: https://api.yourdomain.com/catalog
  • Order Service: https://api.yourdomain.com/order

The API Gateway internally routes these requests to the respective microservices.

the coding blueprint Master Simplified Microservices Communication with YARP API Gateway in ASP.NET Core 9.0

Advanced YARP Features

Centralized Authentication

Add middleware to handle authentication at the gateway level.

app.UseAuthentication();
app.UseAuthorization();
app.MapReverseProxy();

Load Balancing

Distribute traffic across multiple service instances using YARP’s load-balancing feature.

"Clusters": {
  "AuthenticationCluster": {
    "LoadBalancingPolicy": "RoundRobin",
    "Destinations": {
      "AuthService1": { "Address": "https://localhost:7000/" },
      "AuthService2": { "Address": "https://localhost:7003/" }
    }
  }
}

Request Transformation

Modify incoming requests before forwarding them.

builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddTransforms(builderContext =>
    {
        builderContext.RequestTransforms.AddPathPrefix("/api/v1");
    });

Conclusion

By integrating YARP.ReverseProxy in your ASP.NET Core 9.0 application, you can:

  1. Simplify consumer interactions with a single gateway URL.
  2. Centralize routing, authentication, and logging.
  3. Enhance scalability and security in your e-commerce platform.

This approach not only aligns with modern microservices best practices but also improves developer productivity and consumer satisfaction.

Categorized in: