DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Revolutionizing Content Management
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Architecting Scalable ASP.NET Core Web APIs With Abstract Factory Method and Onion Architecture

Trending

  • Monitoring Spring Boot Applications with Prometheus and Grafana
  • Architecting Autonomous Agents: A Deep Dive into Azure AI Foundry Agent Service
  • Security Readiness Checklist: From AI Threats to Software Supply Chain Defense
  • Spring CRUD Generator v1.1.0 Updates
  1. DZone
  2. Data Engineering
  3. Databases
  4. Building a Microservices API Gateway With YARP in ASP.NET Core Web API

Building a Microservices API Gateway With YARP in ASP.NET Core Web API

Let's walk through a more detailed step-by-step process with code for a more comprehensive API Gateway using YARP in ASP.NET Core.

By 
Sardar Mudassar Ali Khan user avatar
Sardar Mudassar Ali Khan
·
Oct. 05, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
7.0K Views

Join the DZone community and get the full member experience.

Join For Free

Let's walk through a more detailed step-by-step process with code for a more comprehensive API Gateway using YARP in ASP.NET Core. We'll consider a simplified scenario with two microservices: UserService and ProductService. The API Gateway will route requests to these services based on the path.

Step 1: Create Microservices

Create two separate ASP.NET Core Web API projects for UserService and ProductService. Use the following commands:

C#
 
dotnet new webapi -n UserService
dotnet new webapi -n ProductService


Step 2: Install YARP Packages

Add the YARP NuGet packages to both microservices projects:

C#
 
# For UserService
dotnet add package Microsoft.ReverseProxy --version 2.11.0
dotnet add package Microsoft.ReverseProxy.Telemetry.Consumption --version 1.0.0

# For ProductService
dotnet add package Microsoft.ReverseProxy --version 2.11.0
dotnet add package Microsoft.ReverseProxy.Telemetry.Consumption --version 1.0.0


Step 3: Configure Microservices

In each Startup.cs file of UserService and ProductService, configure a simple endpoint:

C#
 
// Inside Configure method in Startup.cs for UserService
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapGet("/user", async context =>
    {
        await context.Response.WriteAsync("User Service");
    });
});

// Inside Configure method in Startup.cs for ProductService
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapGet("/product", async context =>
    {
        await context.Response.WriteAsync("Product Service");
    });
});


Step 4: Create API Gateway

Now, create a new ASP.NET Core Web API project for the API Gateway:

C#
 
dotnet new webapi -n ApiGateway


Step 5: Install YARP Package for API Gateway

Add YARP NuGet packages to the ApiGateway project:

C#
 
dotnet add package Microsoft.ReverseProxy --version 2.11.0
dotnet add package Microsoft.ReverseProxy.Telemetry.Consumption --version 1.0.0


Step 6: Configure API Gateway

Update the Startup.cs file in the ApiGateway project:

C#
 
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddReverseProxy()
            .LoadFromConfig(Configuration.GetSection("ReverseProxy"));
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseRouting();

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


Step 7: Configure YARP in appsettings.json

Create an appsettings.json file in the ApiGateway project and configure YARP:

C#
 
{
  "ReverseProxy": {
    "Clusters": {
      "user": {
        "Destinations": {
          "userService": { "Address": "https://localhost:5001" }
        }
      },
      "product": {
        "Destinations": {
          "productService": { "Address": "https://localhost:5002" }
        }
      }
    },
    "Routes": [
      {
        "RouteId": "userRoute",
        "ClusterId": "user",
        "Match": { "Path": "/user/{**catch-all}" }
      },
      {
        "RouteId": "productRoute",
        "ClusterId": "product",
        "Match": { "Path": "/product/{**catch-all}" }
      }
    ]
  }
}


Step 8: Run the Services and Gateway

Run each microservice (UserService and ProductService) and the API Gateway (ApiGateway). Access the gateway at https://localhost:5000 and test the configured routes, such as https://localhost:5000/user and https://localhost:5000/product.

This example provides a basic structure for an API Gateway using YARP in ASP.NET Core, allowing you to route requests to different microservices based on the path. Adjustments and additional features can be implemented based on your specific requirements and the complexities of your microservices architecture.

API ASP.NET ASP.NET Core Web API microservice

Opinions expressed by DZone contributors are their own.

Related

  • Revolutionizing Content Management
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Architecting Scalable ASP.NET Core Web APIs With Abstract Factory Method and Onion Architecture

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook