Skip to main content
ImmutableLog logo
← Back
Minimal APIC#

Minimal API Integration

Minimal API uses the same HTTP pipeline as ASP.NET Core, so it reuses exactly the same `ImmutableLogMiddleware.cs` file. The difference is the registration in `Program.cs` and how you set the event and trail per endpoint via `HttpContext.Items`.

Reuse the middleware

It is a single file for both styles: the middleware sits in the pipeline, before the endpoints, and does not depend on how they were mapped. There is no NuGet package: copy `ImmutableLogMiddleware.cs` from GitHub into your project (the full code is on the ASP.NET Core page). Here we only show the registration and usage in Minimal API endpoints.

Registration in Program.cs

`AddImmutableLog` registers the options, the named `HttpClient` and the middleware. Order matters: call `UseImmutableLog` before mapping the endpoints.

csharp
// Program.cs
using ImmutableLog;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddImmutableLog(o => o.Service = "my-minimal-api");

var app = builder.Build();
app.UseImmutableLog();   // antes de mapear os endpoints

app.MapGet("/users/{id:int}", (int id) => Results.Ok(new { id }));
app.MapPost("/payments", (HttpContext ctx) =>
{
    ctx.Items[ImmutableLogItems.EventName] = "payment.created";
    ctx.Items[ImmutableLogItems.Trail] = "order-7782";
    return Results.Created("/payments/1", new { ok = true });
});
app.Run();

The default values of `ImmutableLogOptions` come from the variables below. Whatever you assign in `AddImmutableLog(o => ...)` wins over the variable. Options: `ApiKey`, `ApiUrl`, `Service`, `Env`, `SkipPaths` (exact match; default `/health` and `/healthz`), `TrustTrailHeader` and `Timeout` (default 5 s).

VariableRequiredDescription
IMTBL_API_KEYYesImmutableLog API key, with the `events:write` scope
IMTBL_URLNoAPI base URL (default `https://api.immutablelog.com`)
IMTBL_SERVICE_NAMENoService name (`meta.service`); default `aspnet-service`
IMTBL_ENVNoEnvironment (`meta.environment` and `meta.env`); default `production`

Without a key, the middleware logs a warning on creation and sends nothing.

Never hardcode the key. Use an environment variable, `dotnet user-secrets` in development, or a secrets manager.

Route template: in Minimal API `http_route` comes from `RouteEndpoint.RoutePattern.RawText` and includes the constraint as written (e.g. `/users/{id:int}`). On a 404 it falls back to the concrete path.

Event and trail per endpoint

Receive the `HttpContext` in the endpoint delegate and set `Items[ImmutableLogItems.EventName]` and `Items[ImmutableLogItems.Trail]`. The middleware reads these values when it builds the event.

csharp
// Receba o HttpContext para definir evento/trilha por endpoint.
app.MapPost("/payments", (HttpContext ctx, PaymentDto dto) =>
{
    ctx.Items[ImmutableLogItems.EventName] = "payment.created";
    ctx.Items[ImmutableLogItems.Trail] = "order-7782";

    // ... business logic ...
    return Results.Ok(new { ok = true, payment_id = "pay_123" });
});

// Trilha por fluxo de negócio:
app.MapPost("/flows/{id}/run", (HttpContext ctx, string id) =>
{
    ctx.Items[ImmutableLogItems.Trail] = $"flow-{id}";
    return Results.Ok(new { status = "ok" });
});

Auto default: http.METHOD.path.

Immutable trail (immutable_trail)

A trail groups related events into a single auditable timeline and goes in `meta.immutable_trail`. Set `ctx.Items[ImmutableLogItems.Trail]` in the endpoint delegate. The value is normalized by the middleware before sending.

The trail cannot be empty, exceed 256 characters, or contain `:`, and violations return `400 invalid_immutable_trail`. That is why the middleware's `SanitizeTrail` replaces `:` with `-`, truncates at 256 and omits the key if it ends up empty.

The `X-Imtbl-Trail` header is optional and off by default. It is only read with `o.TrustTrailHeader = true` and only when the endpoint did not set the trail. The header comes from whoever calls the service, so any caller could hang events on another caller's trail within the same tenant. Turn it on only when the service receives calls exclusively from your own internal services.

Response and status codes

The ingestion API is asynchronous. Success returns 202 (new) or 200 (idempotent duplicate). The middleware does not wait for this response (a rejection only produces a `LogWarning`), so these codes matter mostly if you send events manually.

StatusMeaning
202Event accepted and queued (new)
200Idempotency-Key already exists (duplicate: true)
400Missing/empty Idempotency-Key or invalid_immutable_trail
403Inactive/expired subscription, scope or retention
413payload_too_large (server limit: 16KB)
429monthly_limit_exceeded, do not retry
503mempool_full, transient, retryable

meta fields

Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.

Field in metaWhat it does in the SIEM
event_nameThe event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below.
immutable_trailBecomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user).
typeEvent severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.)
http_method, http_status, http_route, log_level, environment, error_type, error_messageSent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error.
service, env, request_idMetadata: indexed and queryable in the dashboard (search/filters).

client_ip: end-user IP

The problem it solves

Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)

The solution

The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.

How the SIEM handles it

  • Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g. 1.2.3.4:5678) is also silently discarded.
  • Writes to source.ip with maximum precedence (see order below).
  • Stamps imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge.
  • Feeds GeoIP, threat intel and IP-based detection rules.
source.ip precedence:client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IP

Provenance and trust

client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.

How to obtain the IP in your backend

Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).

Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to source.ip.

csharp
using System.Net;

static string? BareIp(string? value)
{
    var v = (value ?? "").Trim();
    if (v.StartsWith('['))
    {
        var end = v.IndexOf(']');
        if (end < 0) return null;
        var rest = v[(end + 1)..];
        if (rest.Length > 0 && !(rest.Length > 1 && rest[0] == ':' && rest[1..].All(char.IsAsciiDigit))) return null;
        v = v[1..end];
    }
    else if (v.Count(c => c == ':') == 1)
    {
        v = v[..v.IndexOf(':')]; // 1.2.3.4:5678 -> 1.2.3.4
    }
    // TryParse aceita formas curtas ("1" vira 0.0.0.1): exija 4 octetos ou um IPv6 (com ':').
    if (v.Contains('%') || !IPAddress.TryParse(v, out var ip)) return null;
    if (!v.Contains(':') && v.Count(c => c == '.') != 3) return null;
    if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4(); // ::ffff:1.2.3.4 -> 1.2.3.4
    return ip.ToString();
}

// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
static string? ClientIp(HttpContext ctx)
{
    var xff = ctx.Request.Headers["X-Forwarded-For"].ToString();
    if (xff.Length > 0 && BareIp(xff.Split(',')[0]) is { } fromXff) return fromXff;
    if (BareIp(ctx.Request.Headers["X-Real-IP"].ToString()) is { } fromXri) return fromXri;
    return BareIp(ctx.Connection.RemoteIpAddress?.ToString());
}

var meta = new Dictionary<string, string> { ["event_name"] = "user.login" };
if (ClientIp(ctx) is { } ip)
    meta["client_ip"] = ip; // sem IP valido, omita a chave (nunca "unknown")

Payload example

json
{
  "payload": "{\"user\":\"bob\",\"action\":\"login\"}",
  "meta": {
    "event_name": "user.login",
    "client_ip": "179.110.4.205",
    "immutable_trail": "user-bob"
  }
}

PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.

This documentation reflects the current integration behavior. For questions or advanced integrations, contact the support team.

Back to C#