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
Newsletter
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

  • The Permission Was Valid. The Action Was Not Authorized.
  • Designing Frontend Applications for Failure, Not Just Success
  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • SSRF Prevention in C#: Securing File Imports From User-Supplied URLs

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Oct. 05, 23 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
7.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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