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. 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:

dotnet new webapi -n UserService
dotnet new webapi -n ProductService

Step 2. Install YARP Packages

Add the YARP NuGet packages to both microservices projects:

# 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:

// 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:

dotnet new webapi -n ApiGateway

Step 5. Install YARP Package for API Gateway

Add YARP NuGet packages to the ApiGateway project:

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:

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:

{
  "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.

Conclusion

Building a microservices API Gateway with YARP in ASP.NET Core Web API provides a flexible and scalable solution for managing and routing traffic in a microservices architecture. By incorporating features such as service discovery, authentication, authorization, load balancing, rate limiting, and logging, you can create a robust and secure gateway that orchestrates communication between diverse microservices. Additionally, considerations like SSL termination, caching, and custom middleware contribute to improved performance and customization. Documentation, testing, and a robust CI/CD pipeline are crucial for maintaining a reliable and well-documented gateway. Overall, this approach empowers developers to efficiently manage and scale microservices while ensuring security, performance, and maintainability.


Similar Articles