Skip to content

API Gateway Template

The ConnectSoft API Gateway Template provides a production-ready solution for building API gateways that serve as the central entry point for distributed systems. Built on .NET 9.0 with Clean Architecture and Domain-Driven Design principles, this template includes comprehensive features for routing, authentication, rate limiting, observability, and multi-tenant support.

Overview

The API Gateway Template generates a custom .NET Core reverse proxy gateway designed from the ground up to support multi-tenant SaaS platforms, enterprise service boundaries, and AI-ready ecosystems. It is a self-contained solution that provides routing, policy injection, JWT validation, observability, and more — all built-in.

Unlike generic gateway solutions, this template provides a Backend for Frontend (BFF) pattern implementation that can be customized for specific channels (web, mobile, admin portals) and orchestrates cross-service flows.

When to Use This Template

Use the API Gateway Template when:

  • Building a central entry point for microservices architecture
  • Creating Backend for Frontend (BFF) layers for specific channels
  • Implementing API aggregation and orchestration
  • Managing cross-cutting concerns (authentication, rate limiting, logging)
  • Building multi-tenant SaaS platforms with tenant isolation
  • Creating API gateways with custom business logic
  • Implementing request/response transformation
  • Building gateways with comprehensive observability

When to Use Microservice Template Instead

Use the Microservice Template when:

  • Building individual backend services
  • Creating domain-specific microservices
  • Implementing business logic services
  • Building services that will be accessed through a gateway

Key Features

Routing and Request Handling

  • Reverse Proxy: Custom reverse proxy implementation for routing requests
  • Request Routing: Configurable routing to backend services
  • Request Transformation: Header rewriting and request modification
  • Response Transformation: Response aggregation and transformation
  • Service Discovery: Integration with service discovery mechanisms
  • Header Propagation: Automatic header propagation to backend services

Authentication and Authorization

  • Multiple Authentication Schemes: JWT Bearer, OpenID Connect, API Key
  • Authorization Policies: RBAC, Claims-based, Scope-based authorization
  • Token Validation: JWT token validation and verification
  • Multi-Tenant Authentication: Tenant-aware authentication and authorization
  • Custom Authentication Handlers: Extensible authentication handler support

Rate Limiting and Throttling

  • Rate Limiting Middleware: ASP.NET Core rate limiting support
  • Global Rate Limiting: Application-wide rate limiting policies
  • Per-Endpoint Rate Limiting: Endpoint-specific rate limits
  • Configurable Policies: Flexible rate limiting configuration

Observability

  • OpenTelemetry Integration: Comprehensive OpenTelemetry support
  • Observability Stack Options: OtelCollector (recommended) or DirectExport
  • Multiple Backends: ELK, Prometheus/Grafana, Seq, Azure Monitor, Application Insights, Jaeger
  • Structured Logging: Serilog-based structured logging
  • Metrics Collection: Custom metrics and performance counters
  • Distributed Tracing: End-to-end request tracing
  • Resource Monitoring: CPU, memory, and resource utilization tracking

Performance and Resilience

  • Response Compression: Gzip and Brotli compression support
  • Caching: Distributed caching (Redis, In-Memory)
  • Request Timeout: Configurable request timeout policies
  • Health Checks: Comprehensive health check endpoints
  • Health Check UI: Visual health check dashboard
  • Circuit Breaker Patterns: Resilience patterns for backend calls

API Documentation

  • Swagger/OpenAPI: Swagger UI integration
  • Scalar: Modern API documentation with Scalar
  • Interactive Testing: Built-in API testing capabilities

Additional Features

  • CORS Support: Cross-Origin Resource Sharing configuration
  • Feature Flags: Microsoft Feature Management integration
  • SignalR: Real-time web functionality (optional)
  • SignalR Backplane: Redis backplane for SignalR scaling
  • Azure App Configuration: Centralized configuration management
  • Docker Support: Containerization with Docker and Docker Compose
  • Kubernetes Deployment: Kubernetes deployment manifests

Generated Structure

The template generates a complete API Gateway solution:

YourApiGatewayName/
├── ConnectSoft.ApiGatewayTemplate.Application/
│   ├── Program.cs
│   ├── appsettings.json
│   └── ...
├── ConnectSoft.ApiGatewayTemplate.ApplicationModel/
│   ├── ApiGatewayRegistrationExtensions.cs
│   ├── AuthenticationExtensions.cs
│   ├── AuthorizationExtensions.cs
│   ├── RateLimitingExtensions.cs
│   └── ...
├── ConnectSoft.ApiGatewayTemplate.Options/
│   ├── ApiGatewayOptions.cs
│   ├── AuthenticationOptions.cs
│   ├── RateLimitingOptions.cs
│   └── ...
├── ConnectSoft.ApiGatewayTemplate.DomainModel/
│   └── ...
├── ConnectSoft.ApiGatewayTemplate.RestApiModel/
│   └── ...
├── ConnectSoft.ApiGatewayTemplate.ServiceModel.SignalR/ (optional)
│   └── ...
├── ConnectSoft.ApiGatewayTemplate.UnitTests/
├── ConnectSoft.ApiGatewayTemplate.AcceptanceTests/
├── ConnectSoft.ApiGatewayTemplate.DockerCompose/ (if Docker enabled)
├── Deployment/
│   ├── docker-compose/
│   └── kubernetes/
└── Docs/

Template Parameters

The template supports extensive customization through parameters:

Parameter Type Required Default CLI Long Name CLI Short Name Description
Framework choice No net9.0 --framework N/A Target framework (currently net9.0)
HttpPort integer No Auto --httpPort --http HTTP endpoint port
HttpsPort integer No Auto --httpsPort --https HTTPS endpoint port
Docker bool No true --docker --d Enable Docker support
HealthCheck bool No true --healthcheck --hck Enable health checks
HealthCheckPath string No /health --healthcheck-path --hp Health check endpoint path
HealthCheckPublisher choice No Seq --healthcheck-publisher --hp-pub Health check publisher (Seq, ApplicationInsights)
HealthCheckUI bool No true --healthcheck-ui --hck-ui Enable health check UI
CORS bool No true --cors --cors Enable CORS support
Swagger bool No true --swagger --sw Enable Swagger UI
Scalar bool No true --scalar --sc Enable Scalar API docs
RateLimiting bool No true --rate-limiting --rl Enable rate limiting
Compression bool No true --compression --comp Enable response compression
DistributedCache choice No None --distributed-cache --cache Distributed cache (Redis, InMemory, None)
UseSignalR bool No false --signalr --sr Enable SignalR
SignalRBackplane choice No None --signalr-backplane --srbp SignalR backplane (None, Redis)
OpenTelemetry bool No true --open-telemetry --o-t Enable OpenTelemetry
ObservabilityStack choice No OtelCollector --observability-stack --obs-stack Observability stack (OtelCollector, DirectExport)
ObservabilityBackend choice No PrometheusGrafana --observability-backend --obs-backend Observability backend (ELK, PrometheusGrafana, Seq, AzureMonitor, ApplicationInsights, Jaeger, All)
FeatureFlags bool No true --feature-flags --f-f Enable feature flags
FeatureFlagsProvider choice No AppSettings --feature-flags-provider --f-f-pr Feature flags provider (AppSettings, AzureAppConfiguration)
AdditionalConfigurationProvider choice No None --config-provider --c-pr Additional config provider (AzureAppConfiguration, None)
UseApplicationInsights bool No false --application-insights --app-ins Enable Application Insights
Authentication bool No false --authentication --auth Enable authentication
ResourceMonitoring bool No true --resource-monitoring --rm Enable resource monitoring
buildDefinitionNumber string No XXX --build-definition-number --bdn Azure DevOps build definition number

Quick Start

Step 1: Create API Gateway

dotnet new connectsoft-apigateway \
  --name MyApiGateway \
  --docker true \
  --authentication true \
  --rate-limiting true \
  --open-telemetry true \
  --observability-stack OtelCollector \
  --observability-backend PrometheusGrafana

Step 2: Configure Gateway Settings

Update appsettings.json with gateway configuration:

{
  "ApiGateway": {
    "ApiGatewayName": "MyApiGateway",
    "StartupWarmupSeconds": 20
  },
  "Routing": {
    "Routes": [
      {
        "RouteId": "backend-service",
        "Match": {
          "Path": "/api/{**catch-all}"
        },
        "Destination": {
          "Address": "https://backend-service.example.com"
        }
      }
    ]
  },
  "Authentication": {
    "Schemes": {
      "Bearer": {
        "Authority": "https://identity.example.com",
        "Audience": "api-gateway"
      }
    }
  },
  "RateLimiting": {
    "GlobalLimiter": {
      "PermitLimit": 100,
      "Window": "00:01:00"
    }
  }
}

Step 3: Configure Routing

Define routes to backend services in configuration or code:

// In Program.cs or routing configuration
app.MapReverseProxy(proxyPipeline =>
{
    proxyPipeline.Use(async (context, next) =>
    {
        // Custom middleware logic
        await next();
    });

    proxyPipeline.UseRouting();
    proxyPipeline.UseEndpoints();
});

Step 4: Run the Gateway

# Development
dotnet run --project ConnectSoft.ApiGatewayTemplate.Application

# Or with Docker
docker-compose up

Architecture

Design Principles

  • Custom Reverse Proxy: Purpose-built .NET Core reverse proxy (not YARP/Envoy)
  • Clean Architecture: Separation of concerns across layers
  • Domain-Driven Design: Domain model for gateway concepts
  • Security-First: Authentication and authorization built-in
  • Observability-Driven: Comprehensive logging, metrics, and tracing
  • Multi-Tenant Ready: Tenant isolation and management support
  • Extensible: Custom middleware and policy injection points

Gateway Flow

sequenceDiagram
    participant Client
    participant Gateway as API Gateway
    participant Auth as Auth Service
    participant Backend as Backend Service

    Client->>Gateway: Request
    Gateway->>Gateway: Rate Limiting Check
    Gateway->>Auth: Validate Token
    Auth-->>Gateway: Token Valid
    Gateway->>Gateway: Apply Policies
    Gateway->>Backend: Forward Request
    Backend-->>Gateway: Response
    Gateway->>Gateway: Transform Response
    Gateway-->>Client: Response
Hold "Alt" / "Option" to enable pan & zoom

Integration with AI Factory

The API Gateway Template is used by:

  • API Gateway Generator Agent: Generates API gateway projects
  • Solution Architect Agent: Designs gateway architecture
  • Backend Developer Agent: Creates BFF layers for frontend channels
  • Platform Generator Agent: Includes gateways in platform projects

Best Practices

Routing

  • Route Organization: Organize routes by domain or channel
  • Service Discovery: Use service discovery for dynamic routing
  • Fallback Routes: Implement fallback routes for resilience
  • Route Versioning: Support API versioning in routes

Security

  • Token Validation: Always validate tokens before forwarding
  • Rate Limiting: Implement appropriate rate limits per endpoint
  • CORS Configuration: Configure CORS policies carefully
  • Header Sanitization: Sanitize headers before forwarding

Observability

  • Correlation IDs: Propagate correlation IDs through requests
  • Structured Logging: Use structured logging for all operations
  • Metrics Collection: Collect metrics for all gateway operations
  • Distributed Tracing: Enable distributed tracing for request flows

Performance

  • Caching: Use distributed caching for frequently accessed data
  • Compression: Enable response compression for large payloads
  • Connection Pooling: Configure HTTP client connection pooling
  • Timeout Configuration: Set appropriate timeouts for backend calls