Skip to main content
ImmutableLog logo
BackC# / .NET

C# / .NET

Complete integration guide for ImmutableLog in C# / .NET. Automatic middleware for ASP.NET Core and Minimal API — or a typed HttpClient client for workers, BackgroundServices, and jobs. Sending is async and does not block the response.

Typed HttpClient client

Use ImmutableLogClient to send events directly to ImmutableLog without depending on the web pipeline. Ideal for workers, BackgroundService, queue consumers, and any .NET code that needs to record events.

csharp
// ImmutableLogClient.cs
using System.Net.Http.Json;
using System.Text.Json;

public sealed class ImmutableLogClient
{
    private readonly HttpClient _http;
    private readonly string _apiKey;
    private readonly string _service;
    private readonly string _env;

    public ImmutableLogClient(HttpClient http, string apiKey, string service, string env)
    {
        _http = http;
        _apiKey = apiKey;
        _service = service;
        _env = env;
    }

    public async Task SendEventAsync(
        string eventName,
        string kind,                         // "success" | "info" | "error"
        object payload,
        string? immutableTrail = null,
        CancellationToken ct = default)
    {
        var requestId = Guid.NewGuid().ToString();
        var trail = SanitizeTrail(immutableTrail);

        // Todos os valores de meta precisam ser strings.
        var meta = new Dictionary<string, string>
        {
            ["type"] = kind,
            ["event_name"] = eventName,
            ["service"] = _service,
            ["request_id"] = requestId,
            ["env"] = _env,
        };
        if (trail is not null) meta["immutable_trail"] = trail;

        var body = new
        {
            payload = JsonSerializer.Serialize(payload),
            meta,
        };

        using var req = new HttpRequestMessage(HttpMethod.Post, "/v1/events")
        {
            Content = JsonContent.Create(body),
        };
        req.Headers.Add("Authorization", $"Bearer {_apiKey}");
        // Idempotency-Key e OBRIGATORIO (sem ele a API responde 400).
        req.Headers.Add("Idempotency-Key", $"{eventName}-{requestId}");
        req.Headers.Add("Request-Id", requestId);
        // Timezone do cliente — usado pelo dashboard para exibir os timestamps.
        req.Headers.Add("X-Client-TZ", "America/Sao_Paulo");
        req.Headers.Add("X-Client-Offset-Minutes", "-180");
        if (trail is not null) req.Headers.Add("X-Imtbl-Trail", trail);

        using var res = await _http.SendAsync(req, ct);
        res.EnsureSuccessStatusCode();
    }

    // Normaliza o immutable_trail (trim, nao-vazio, max 256, sem ':').
    // O servidor responde 400 invalid_immutable_trail se a regra for violada.
    public static string? SanitizeTrail(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return null;
        var v = value.Trim().Replace(":", "-");
        if (v.Length > 256) v = v[..256];
        return v;
    }
}

// Program.cs — registro via IHttpClientFactory (typed client)
builder.Services.AddHttpClient("immutablelog", c =>
{
    c.BaseAddress = new Uri(
        Environment.GetEnvironmentVariable("IMTBL_URL") ?? "https://api.immutablelog.com");
    c.Timeout = TimeSpan.FromSeconds(5);
});
builder.Services.AddSingleton(sp =>
{
    var http = sp.GetRequiredService<IHttpClientFactory>().CreateClient("immutablelog");
    return new ImmutableLogClient(http,
        Environment.GetEnvironmentVariable("IMTBL_API_KEY") ?? "",
        "my-service", "production");
});

// Uso (fire-and-forget — descarta a Task; capture exceções se precisar):
// _ = client.SendEventAsync("user.created", "success",
//         new { user_id = "usr_123", plan = "pro" }, immutableTrail: "order-7782");

Use IHttpClientFactory to reuse connections. For fire-and-forget, discard the Task with _ = ...; wrap in try/catch if you want to handle send failures.

Retry with exponential backoff

For high-availability production, add retry with exponential backoff. ImmutableLog returns 202 on success and 200 on an idempotent duplicate — never retry on 429 (monthly limit reached).

csharp
// Retry em erros transitorios (nunca em 429).
public async Task SendWithRetryAsync(
    string eventName, string kind, object payload,
    string? trail = null, int maxAttempts = 3, CancellationToken ct = default)
{
    var delay = TimeSpan.FromMilliseconds(500);

    for (var attempt = 0; attempt < maxAttempts; attempt++)
    {
        try
        {
            await SendEventAsync(eventName, kind, payload, trail, ct);
            return;
        }
        catch (HttpRequestException ex) when (ex.StatusCode == (System.Net.HttpStatusCode)429)
        {
            // 429 = limite mensal — nao fazer retry.
            return;
        }
        catch (HttpRequestException) when (attempt + 1 < maxAttempts)
        {
            await Task.Delay(delay, ct);
            delay *= 2; // 500ms -> 1s -> 2s
        }
    }
}

Sensitive data hashing

Never send raw personal data (email, CPF, IP) to ImmutableLog. Use SHA-256 to generate a deterministic digest — traceable without exposing the original data.

csharp
using System.Security.Cryptography;
using System.Text;

// Faz o hash de dados sensiveis antes de enviar — nunca logue PII bruto.
static string Sha256Hex(string data)
{
    var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(data));
    return Convert.ToHexString(bytes).ToLowerInvariant();
}

// Uso no payload do evento:
var payload = new
{
    user_id    = "usr_123",
    email_hash = Sha256Hex("user@example.com"),
    ip_hash    = Sha256Hex("192.168.1.1"),
};

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 loginauthentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. See the section below.
immutable_trailBecomes imtbl.immutable_trail — 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.)
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 — it does not drop the event.
  • 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 is spoofable by whoever controls that backend. However it is self-contained to 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

Take the first IP from X-Forwarded-For (closest to the user); as a fallback, use the connection IP.

csharp
static string? ClientIp(HttpContext ctx)
{
    var xff = ctx.Request.Headers["X-Forwarded-For"].ToString();
    if (!string.IsNullOrEmpty(xff))
        return xff.Split(',')[0].Trim(); // primeiro hop = IP do usuario
    return ctx.Connection.RemoteIpAddress?.ToString();
}

var meta = new Dictionary<string, string>
{
    ["event_name"] = "user.login",
    ["client_ip"] = ClientIp(ctx) ?? "",
};

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 API behavior. For questions or advanced integrations, contact the support team.