Getting started with the Router

This guide builds a gateway and one microservice from the Router NuGet packages, runs them on one machine, and calls the service through the gateway. It takes about fifteen minutes. Every file the two projects need is on this page.

At the end you have:

  • a gateway that accepts microservices over TCP, checks JWT bearer tokens and routes HTTP requests;
  • a billing service with two endpoints, discovered at compile time by the source generator;
  • requests that succeed, and requests the gateway refuses with 401 and 403.

Before you start

  • The .NET 10 SDK.
  • A nuget.config that maps StellaOps.* to the Stella Ops feed, as Installing Stella Ops packages shows. Put it in the folder that will hold both projects.
  • curl, or any HTTP client.

The concepts behind the steps (gateway, microservice, transport, endpoint claims) are explained in the Router overview.

Step 1: Create the gateway

A gateway is an ASP.NET Core application that hosts the gateway pipeline and the server half of at least one transport. This one uses TCP, the simplest transport for one machine.

dotnet new web -o src/Examples.Gateway
cd src/Examples.Gateway
dotnet add package StellaOps.Router.Gateway.Hosting --prerelease
dotnet add package StellaOps.Router.Transport.Tcp.Server --prerelease

The project file then references the two packages. The project files on this page write the version as $(RouterPackageVersion), one property for every Router package; dotnet add package writes the version number instead. Use one version for all Router packages.

<PackageReference Include="StellaOps.Router.Gateway.Hosting" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Router.Transport.Tcp.Server" Version="$(RouterPackageVersion)" />

Replace Program.cs:

using System.Net;
using Microsoft.AspNetCore.HttpOverrides;
using StellaOps.Router.Gateway.Hosting;
using StellaOps.Router.Transport.Tcp.Server;

var builder = WebApplication.CreateBuilder(args);

// The gateway pipeline: the TCP server transport (Gateway:Transports:Tcp), the routing state built
// from the microservices' HELLO frames, JWT bearer authentication (Authentication:Schemes:Bearer),
// the endpoint claims check, health, metrics, the router administration endpoints and the licence
// monitor. The host stops at startup when JWT bearer authentication is not configured.
builder.AddRouterGatewayHost(typeof(TcpTransportServerPlugin).Assembly);

// Behind a reverse proxy: take the caller's address and scheme from X-Forwarded-For and
// X-Forwarded-Proto, but only from the proxies listed in ReverseProxy:KnownProxies (loopback by default).
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    foreach (var proxy in builder.Configuration.GetSection("ReverseProxy:KnownProxies").Get<string[]>() ?? [])
    {
        options.KnownProxies.Add(IPAddress.Parse(proxy));
    }
});

var app = builder.Build();
app.UseForwardedHeaders();

// Optional hardening: the gateway host already removes the identity headers (X-StellaOps-Tenant,
// X-StellaOps-Scopes, the identity envelope and the rest) from every routed request. This middleware
// also removes every other X-StellaOps-* request header, so no caller-supplied one reaches a service.
app.Use((context, next) =>
{
    foreach (var name in context.Request.Headers.Keys
                 .Where(key => key.StartsWith("X-StellaOps-", StringComparison.OrdinalIgnoreCase))
                 .ToList())
    {
        context.Request.Headers.Remove(name);
    }

    return next(context);
});

app.UseRouterGatewayHost();
await app.RunAsync();

AddRouterGatewayHost registers the gateway services and the transports whose assemblies it is given. UseRouterGatewayHost adds authentication, health, metrics, the router administration endpoints, and the routing pipeline for every other request. The forwarded-headers part matters only behind a reverse proxy, and the header-removal middleware is optional hardening.

Replace appsettings.json. It names the gateway node and turns on the TCP listener:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Gateway": {
    "Node": {
      "Region": "demo",
      "NodeId": "gw-demo-01"
    },
    "Transports": {
      "Tcp": {
        "Enabled": true,
        "BindAddress": "127.0.0.1",
        "Port": 9100
      }
    }
  }
}

Replace Properties/launchSettings.json. It sets the URL, the Development environment and the insecure-transport switch that TCP needs (Step 6):

{
  "profiles": {
    "Examples.Gateway": {
      "commandName": "Project",
      "applicationUrl": "http://localhost:5080",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS": "true"
      }
    }
  }
}

Step 2: Give the gateway a token issuer

The gateway refuses to start until JWT bearer authentication is configured: a key source, an issuer and an audience. For a local run, dotnet user-jwts stores a signing key in the project’s user secrets and prints tokens signed with it. In src/Examples.Gateway:

dotnet user-jwts create --audience router-gateway \
  --scope invoices:write --scope invoices:read --scope router:routing:read

Expected result: the command prints a token. Keep it; Step 6 sends it. The command also writes the issuer and audience into appsettings.Development.json, which the Development environment reads.

In production the gateway reads the same settings from your OpenID Connect provider instead: Router gateway host.

Step 3: Create the microservice

cd ../..
dotnet new console -o src/Examples.Billing.Microservice
cd src/Examples.Billing.Microservice
dotnet add package StellaOps.Microservice --prerelease
dotnet add package StellaOps.Microservice.SourceGen --prerelease
dotnet add package StellaOps.Router.Transport.Tcp --prerelease
dotnet add package StellaOps.Router.Transport.Tls --prerelease
dotnet add package Microsoft.Extensions.Hosting

The packages:

<PackageReference Include="StellaOps.Microservice" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Microservice.SourceGen" Version="$(RouterPackageVersion)" PrivateAssets="all" />
<!-- The generic host (Host.CreateApplicationBuilder); the Router packages need only its abstractions. -->
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.1" />
<PackageReference Include="StellaOps.Router.Transport.Tcp" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Router.Transport.Tls" Version="$(RouterPackageVersion)" />
  • StellaOps.Microservice is the SDK: endpoint registration, the connection to the gateway and the request dispatcher.
  • StellaOps.Microservice.SourceGen is a development dependency. It runs in the compiler, finds the endpoint classes and generates their registration, so the service needs no reflection at start-up. Keep PrivateAssets="all" on its reference, as above, so it does not flow to other projects.
  • StellaOps.Router.Transport.Tcp is the client half of the TCP transport, which this guide uses; StellaOps.Router.Transport.Tls, the client half of the TLS transport, is for production.
  • Microsoft.Extensions.Hosting provides the generic host. The Router packages need only its abstractions, so you add the host yourself.

Add this item group to the project file, so the build copies microservice.yaml (Step 5) beside the executable:

<ItemGroup>
  <!-- microservice.yaml beside the executable, where ConfigFilePath looks for it. -->
  <Content Include="microservice.yaml" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

Step 4: Add the endpoints

An endpoint is a class with [StellaEndpoint] that implements IStellaEndpoint<TRequest, TResponse>. The SDK reads the JSON request body into TRequest and writes the returned TResponse as JSON. Create Endpoints/CreateInvoiceEndpoint.cs:

using Microsoft.Extensions.Logging;
using StellaOps.Microservice;

namespace Examples.Billing.Microservice.Endpoints;

/// <summary>
/// Request model for creating an invoice.
/// </summary>
public sealed record CreateInvoiceRequest
{
    public required string CustomerId { get; init; }
    public required decimal Amount { get; init; }
    public string? Description { get; init; }
    public List<LineItem> LineItems { get; init; } = [];
}

/// <summary>
/// Line item for an invoice.
/// </summary>
public sealed record LineItem
{
    public required string Description { get; init; }
    public required decimal Amount { get; init; }
    public int Quantity { get; init; } = 1;
}

/// <summary>
/// Response model after creating an invoice.
/// </summary>
public sealed record CreateInvoiceResponse
{
    public required string InvoiceId { get; init; }
    public required DateTime CreatedAt { get; init; }
    public required string Status { get; init; }
}

/// <summary>
/// Endpoint for creating a new invoice.
/// Demonstrates a typed endpoint with JSON request/response.
/// </summary>
[StellaEndpoint("POST", "/invoices", TimeoutSeconds = 30)]
public sealed class CreateInvoiceEndpoint : IStellaEndpoint<CreateInvoiceRequest, CreateInvoiceResponse>
{
    private readonly ILogger<CreateInvoiceEndpoint> _logger;

    public CreateInvoiceEndpoint(ILogger<CreateInvoiceEndpoint> logger)
    {
        _logger = logger;
    }

    public Task<CreateInvoiceResponse> HandleAsync(
        CreateInvoiceRequest request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Creating invoice for customer {CustomerId} with amount {Amount}",
            request.CustomerId,
            request.Amount);

        // Simulate invoice creation
        var invoiceId = $"INV-{Guid.NewGuid():N}".ToUpperInvariant()[..16];

        return Task.FromResult(new CreateInvoiceResponse
        {
            InvoiceId = invoiceId,
            CreatedAt = DateTime.UtcNow,
            Status = "draft"
        });
    }
}

The second endpoint takes its input from the path: the SDK sets Id from the {id} segment, because the request type has a property of that name. Create Endpoints/GetInvoiceEndpoint.cs:

using Microsoft.Extensions.Logging;
using StellaOps.Microservice;

namespace Examples.Billing.Microservice.Endpoints;

/// <summary>
/// Request model for getting an invoice.
/// </summary>
public sealed record GetInvoiceRequest
{
    public required string Id { get; init; }
}

/// <summary>
/// Response model for an invoice.
/// </summary>
public sealed record GetInvoiceResponse
{
    public required string InvoiceId { get; init; }
    public required string CustomerId { get; init; }
    public required decimal Amount { get; init; }
    public required string Status { get; init; }
    public required DateTime CreatedAt { get; init; }
    public DateTime? PaidAt { get; init; }
}

/// <summary>
/// Endpoint for retrieving an invoice by ID.
/// Demonstrates a GET endpoint with path parameters. microservice.yaml makes it require the
/// scope invoices:read, which the gateway checks before it dispatches the request.
/// </summary>
[StellaEndpoint("GET", "/invoices/{id}", TimeoutSeconds = 10)]
public sealed class GetInvoiceEndpoint : IStellaEndpoint<GetInvoiceRequest, GetInvoiceResponse>
{
    private readonly ILogger<GetInvoiceEndpoint> _logger;

    public GetInvoiceEndpoint(ILogger<GetInvoiceEndpoint> logger)
    {
        _logger = logger;
    }

    public Task<GetInvoiceResponse> HandleAsync(
        GetInvoiceRequest request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Fetching invoice {InvoiceId}", request.Id);

        // Simulate invoice lookup
        return Task.FromResult(new GetInvoiceResponse
        {
            InvoiceId = request.Id,
            CustomerId = "CUST-001",
            Amount = 199.99m,
            Status = "paid",
            CreatedAt = DateTime.UtcNow.AddDays(-7),
            PaidAt = DateTime.UtcNow.AddDays(-1)
        });
    }
}

Step 5: Register the service

Replace Program.cs. It creates a generic host, describes the service, chooses the transport and registers the endpoint classes. The TLS branch runs only when the configuration has a Router:Transport:Tls section; this guide has none, so the service runs over TCP (Deployment shows the TLS form):

using Examples.Billing.Microservice.Endpoints;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StellaOps.Microservice;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Transport.Tcp;
using StellaOps.Router.Transport.Tls;

var builder = Host.CreateApplicationBuilder(args);

// The gateway to connect to: Router:Host and Router:Port (environment Router__Host, Router__Port).
var gatewayHost = builder.Configuration["Router:Host"] ?? "127.0.0.1";
var gatewayPort = builder.Configuration.GetValue("Router:Port", 9100);
// The transport: TCP for development, TLS with a client certificate when the configuration has a
// Router:Transport:Tls section (production).
var tls = builder.Configuration.GetSection("Router:Transport:Tls");
var transportType = tls.Exists() ? TransportType.Certificate : TransportType.Tcp;

builder.Services.AddStellaMicroservice(options =>
{
    options.ServiceName = "billing";
    options.Version = "1.0.0";
    options.Region = "demo";
    options.InstanceId = builder.Configuration["Router:InstanceId"] ?? $"billing-{Environment.MachineName}";
    // Endpoint overrides (timeouts, streaming, required scopes) read from the output directory.
    options.ConfigFilePath = Path.Combine(AppContext.BaseDirectory, "microservice.yaml");
    // Below the gateway's degraded threshold (Gateway:Health:DegradedThreshold; 20 s in effect by default).
    options.HeartbeatInterval = TimeSpan.FromSeconds(10);
    options.Routers =
    [
        new RouterEndpointConfig { Host = gatewayHost, Port = gatewayPort, TransportType = transportType }
    ];
});

// TCP is for development: both ends refuse it unless STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS is true.
if (!tls.Exists())
{
    builder.Services.AddTcpTransportClient(options =>
    {
        options.Host = gatewayHost;
        options.Port = gatewayPort;
    });
}

// Production: TLS, with the client certificate and the other TLS options from Router:Transport:Tls.
if (tls.Exists())
{
    builder.Services.AddTlsTransportClient(options =>
    {
        tls.Bind(options);
        options.Host = gatewayHost;
        options.Port = gatewayPort;
    });
}

builder.Services.AddScoped<CreateInvoiceEndpoint>();
builder.Services.AddScoped<GetInvoiceEndpoint>();

await builder.Build().RunAsync();

Three settings matter on the first run:

SettingWhy
ServiceName, Version, RegionRequired. The gateway groups instances by service name and version, and prefers instances in its own region.
HeartbeatInterval = 10 secondsWith its default settings the gateway marks an instance degraded after 20 seconds without a heartbeat, and stops routing to it after 30 seconds. 10 seconds is the SDK default; the sample sets it explicitly. A longer interval needs the gateway’s thresholds raised; the service logs a warning at start-up when the interval is longer than 30 seconds.
The TCP client’s Host and PortThe transport client connects there: Router:Host and Router:Port from configuration, 127.0.0.1 and 9100 by default. Set Routers to the same address: the SDK requires at least one entry and names the connection after it.

To require a scope for an endpoint, list the endpoint in microservice.yaml and set ConfigFilePath, as Program.cs does. The gateway then checks the scope before it dispatches the request. Create microservice.yaml beside the project file:

# Endpoint overrides for the billing service (keys: method, path, defaultTimeout, supportsStreaming,
# requiringClaims). The gateway enforces the claims the service publishes: a caller without a valid
# token gets 401, a caller without the scope 403.

endpoints:
  - method: POST
    path: /invoices
    defaultTimeout: 45s
    requiringClaims:
      - type: "scope"
        value: "invoices:write"

  - method: GET
    path: /invoices/{id}
    requiringClaims:
      - type: "scope"
        value: "invoices:read"

Create Properties/launchSettings.json. It sets the Development environment and the insecure-transport switch that TCP needs:

{
  "profiles": {
    "Examples.Billing.Microservice": {
      "commandName": "Project",
      "environmentVariables": {
        "DOTNET_ENVIRONMENT": "Development",
        "STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS": "true"
      }
    }
  }
}

Step 6: Run and call the service

TCP sends requests unencrypted, so both ends refuse it unless STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS is true. The two launchSettings.json files set it, and dotnet run reads them. To start the projects without their launch settings, set the variables yourself:

# The gateway, in src/Examples.Gateway
STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS=true ASPNETCORE_ENVIRONMENT=Development \
  dotnet run --no-launch-profile --urls http://localhost:5080
# The service, in src/Examples.Billing.Microservice
STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS=true DOTNET_ENVIRONMENT=Development \
  dotnet run --no-launch-profile
  1. Start the gateway. In src/Examples.Gateway:

    dotnet run
    

    Expected result: the gateway listens on http://localhost:5080 and on TCP port 9100.

  2. Start the service in a second terminal. In src/Examples.Billing.Microservice:

    dotnet run
    

    Expected result: the log shows Discovered 2 endpoints via source generation and a connection to 127.0.0.1:9100.

  3. Create an invoice with the token from Step 2:

    TOKEN='<token printed by dotnet user-jwts create>'
    curl -i -X POST http://localhost:5080/invoices \
      -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
      -d '{"customerId":"CUST-001","amount":99.99,"description":"Sample"}'
    

    Expected result: 200 and a JSON body with invoiceId, createdAt and "status":"draft".

  4. Read an invoice:

    curl -i http://localhost:5080/invoices/INV-001 -H "Authorization: Bearer $TOKEN"
    

    Expected result: 200 and the invoice INV-001.

  5. Try the refusals:

    RequestResultWhy
    The same request without the Authorization header401The gateway requires an authenticated caller for every endpoint of an endpoint class.
    A token without invoices:read (dotnet user-jwts create --audience router-gateway --scope invoices:write) on GET /invoices/INV-001403microservice.yaml publishes invoices:read as a required claim.
    GET http://localhost:5080/unknown with a token404No connected service registers the path.

What happened

  1. The service connected to the gateway over TCP and sent a HELLO frame with its name, version, region and endpoints.
  2. The gateway added the endpoints to its routing state.
  3. For each HTTP request, the gateway matched the method and path to an endpoint, checked the caller’s token against the endpoint’s claims, and sent the request to an instance of the service.
  4. The service dispatched the request to the endpoint class and sent the response back over the same connection.

Pitfalls

  • The gateway exits at start-up with a JWT message. It needs a key source, ValidIssuer(s) and ValidAudience(s) under Authentication:Schemes:Bearer. Run Step 2, and run the gateway in the Development environment so it reads the user secrets.
  • The service logs a refusal of an insecure transport. Set STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS=true for both processes, or use the TLS transport (Transports).
  • The service connects but requests return 503 with No instances available now and then. The heartbeat interval is longer than the gateway’s thresholds. Set HeartbeatInterval as in Step 5.
  • dotnet user-jwts tokens expire. Create a new one when the gateway answers 401 to a request that worked before.
  • Without the source generator the service still runs. It falls back to discovery by reflection and logs no Discovered ... via source generation line. Add StellaOps.Microservice.SourceGen to get compile-time discovery and its diagnostics.

Next steps

GoalRead
Understand the partsRouter overview
Write more endpoint kindsMicroservice SDK
Choose the packages for each projectRouter packages
Upload and download filesFile uploads and downloads
Encrypt the connections and require client certificatesTransports
Protect tokens, claims and the transport portsSecurity
Run the gateway and the services in production, or in containersDeployment