Skip to main content
ImmutableLog logo
← Back
ASP.NET CoreC#

ASP.NET Core Integration

Integrate ImmutableLog into any ASP.NET Core application with an `IMiddleware` that captures HTTP requests (except `OPTIONS` and the `SkipPaths` entries). The same file serves MVC/controllers and Minimal API. Sending runs in `Task.Run`: the response does not wait for ImmutableLog, and a send failure only produces a `LogWarning`.

Middleware code

There is no NuGet package: copy the `ImmutableLogMiddleware.cs` file from GitHub into your project (e.g. `Infrastructure/ImmutableLogMiddleware.cs`). It only uses the ASP.NET Core shared framework (.NET 6 or newer, `Microsoft.NET.Sdk.Web` project). The file declares `namespace ImmutableLog;`: import it with `using ImmutableLog;` or change the namespace to yours. An unhandled exception also produces an event, with status 500 and `error_*`.

csharp
// ImmutableLog middleware for ASP.NET Core (.NET 6+): MVC/controllers and Minimal API.
//
// Copy this file into your project and register it:
//   builder.Services.AddImmutableLog(o => o.Service = "my-api");
//   app.UseImmutableLog();
// Only the ASP.NET Core shared framework is needed (no NuGet package).

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace ImmutableLog;

public sealed class ImmutableLogOptions
{
    public string ApiKey { get; set; } = FromEnv("IMTBL_API_KEY") ?? "";
    public string ApiUrl { get; set; } = FromEnv("IMTBL_URL") ?? "https://api.immutablelog.com";
    public string Service { get; set; } = FromEnv("IMTBL_SERVICE_NAME") ?? "aspnet-service";
    public string Env { get; set; } = FromEnv("IMTBL_ENV") ?? "production";

    /// <summary>Exact paths that never generate an event.</summary>
    public HashSet<string> SkipPaths { get; set; } = new(StringComparer.Ordinal) { "/health", "/healthz" };

    /// <summary>
    /// Read <c>X-Imtbl-Trail</c> from the incoming request when the endpoint sets no trail.
    /// Off by default: the header is controlled by whoever calls the service.
    /// </summary>
    public bool TrustTrailHeader { get; set; }

    public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5);

    private static string? FromEnv(string name)
    {
        var v = Environment.GetEnvironmentVariable(name);
        return string.IsNullOrWhiteSpace(v) ? null : v;
    }
}

/// <summary>Keys an endpoint sets in <c>HttpContext.Items</c> to customise the event.</summary>
public static class ImmutableLogItems
{
    public const string EventName = "imtbl.eventName";
    public const string Trail = "imtbl.trail";
}

public sealed class ImmutableLogMiddleware : IMiddleware
{
    internal const string HttpClientName = "immutablelog";
    private const int MaxErrorMessage = 500;
    private const int MaxPath = 2048;
    private const int MaxUserAgent = 512;
    private const int MaxTrail = 256;

    private readonly IHttpClientFactory _httpFactory;
    private readonly ImmutableLogOptions _opts;
    private readonly ILogger<ImmutableLogMiddleware> _log;

    public ImmutableLogMiddleware(IHttpClientFactory httpFactory, ImmutableLogOptions opts, ILogger<ImmutableLogMiddleware> log)
    {
        _httpFactory = httpFactory;
        _opts = opts;
        _log = log;
        if (string.IsNullOrEmpty(opts.ApiKey))
            log.LogWarning("[ImmutableLog] IMTBL_API_KEY is empty: no event will be sent");
    }

    public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
    {
        var req = ctx.Request;
        // Preflight and skipped paths never generate an event.
        if (HttpMethods.IsOptions(req.Method) || _opts.SkipPaths.Contains(req.Path.Value ?? ""))
        {
            await next(ctx);
            return;
        }

        var started = Stopwatch.GetTimestamp();
        var method = req.Method;
        var path = req.Path.Value ?? "/";
        var userAgent = req.Headers.UserAgent.ToString();
        var clientIp = ClientIp(req.Headers["X-Forwarded-For"].ToString(), req.Headers["X-Real-IP"].ToString(),
            ctx.Connection.RemoteIpAddress);
        var headerTrail = _opts.TrustTrailHeader ? req.Headers["X-Imtbl-Trail"].ToString() : null;

        Exception? caught = null;
        try
        {
            await next(ctx);
        }
        catch (Exception ex)
        {
            caught = ex;
            throw;
        }
        finally
        {
            // Everything is copied out of the HttpContext HERE, on the request thread: the
            // context is pooled and recycled once the request ends, so the background send
            // below never touches it.
            try
            {
                // An exception that escapes the pipeline has not become a response yet: the
                // server answers it with 500. If the response already started, its status stands.
                var status = caught != null && !ctx.Response.HasStarted ? 500 : ctx.Response.StatusCode;
                // UseExceptionHandler registered after this middleware swallows the exception and
                // leaves it in IExceptionHandlerFeature.
                var error = caught ?? ctx.Features.Get<IExceptionHandlerFeature>()?.Error;
                var evt = new EventFacts(
                    Method: method,
                    Path: path,
                    // Route template: "/users/{id}" (Minimal API) or "users/{id}" (attribute routing,
                    // normalised to a leading "/"). No RouteEndpoint on a 404: falls back to the path.
                    Route: RouteTemplate(ctx.GetEndpoint()),
                    Status: status,
                    LatencyMs: (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds,
                    UserAgent: userAgent,
                    ClientIp: clientIp,
                    EventName: ctx.Items[ImmutableLogItems.EventName] as string,
                    Trail: ctx.Items[ImmutableLogItems.Trail] as string ?? headerTrail,
                    ErrorType: error?.GetType().FullName,
                    ErrorMessage: error?.Message);
                if (!string.IsNullOrEmpty(_opts.ApiKey))
                    _ = Task.Run(() => SendAsync(evt)); // fire and forget: never delays the response
            }
            catch (Exception ex)
            {
                _log.LogWarning(ex, "[ImmutableLog] failed to build event");
            }
        }
    }

    private sealed record EventFacts(
        string Method, string Path, string? Route, int Status, long LatencyMs, string UserAgent,
        string? ClientIp, string? EventName, string? Trail, string? ErrorType, string? ErrorMessage);

    private async Task SendAsync(EventFacts e)
    {
        try
        {
            var kind = e.Status >= 400 ? "error" : e.Status >= 300 ? "info" : e.Status >= 200 ? "success" : "info";
            var requestId = Guid.NewGuid().ToString();
            var path = Truncate(e.Path, MaxPath);
            var eventName = string.IsNullOrEmpty(e.EventName) ? $"http.{e.Method}.{path}" : e.EventName;
            var trail = SanitizeTrail(e.Trail);

            var payload = new Dictionary<string, object?>
            {
                ["id"] = Guid.NewGuid().ToString(),
                ["kind"] = kind,
                ["message"] = $"{e.Method} {path} -> {e.Status}",
                ["timestamp"] = DateTimeOffset.UtcNow.ToString("o"),
                ["context"] = new Dictionary<string, object?>
                {
                    ["ip"] = e.ClientIp ?? "unknown",
                    ["user_agent"] = Truncate(e.UserAgent, MaxUserAgent),
                },
                ["request"] = new Dictionary<string, object?>
                {
                    ["request_id"] = requestId, ["method"] = e.Method, ["path"] = path,
                },
                ["metrics"] = new Dictionary<string, object?>
                {
                    ["latency_ms"] = e.LatencyMs, ["status_code"] = e.Status,
                },
                ["severity"] = kind == "error" ? "high" : "low",
            };
            if (kind == "error")
            {
                var err = new Dictionary<string, object?>
                {
                    ["status_code"] = e.Status,
                    ["retryable"] = e.Status is 408 or 429 or 500 or 502 or 503 or 504,
                };
                if (e.ErrorType != null)
                {
                    err["exception"] = e.ErrorType;
                    err["exception_message"] = Truncate(e.ErrorMessage ?? "", MaxErrorMessage);
                }
                payload["error"] = err;
            }

            // meta is a string -> string map in the core: Dictionary<string, string>, never object.
            var meta = new Dictionary<string, string>
            {
                ["type"] = kind,
                ["event_type"] = kind,
                ["event_name"] = eventName,
                ["service"] = _opts.Service,
                ["request_id"] = requestId,
                // "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
                ["env"] = _opts.Env,
                ["environment"] = _opts.Env,
                ["http_method"] = e.Method,
                ["http_status"] = e.Status.ToString(System.Globalization.CultureInfo.InvariantCulture),
                ["http_route"] = string.IsNullOrEmpty(e.Route) ? path : e.Route,
                ["log_level"] = kind == "error" ? "error" : kind == "warning" ? "warn" : kind == "debug" ? "debug" : "info",
            };
            if (e.ClientIp != null) meta["client_ip"] = e.ClientIp;
            if (e.ErrorType != null)
            {
                meta["error_type"] = e.ErrorType;
                if (!string.IsNullOrEmpty(e.ErrorMessage)) meta["error_message"] = Truncate(e.ErrorMessage, MaxErrorMessage);
            }
            if (trail != null) meta["immutable_trail"] = trail;

            var body = JsonSerializer.Serialize(new Dictionary<string, object>
            {
                ["payload"] = JsonSerializer.Serialize(payload),
                ["meta"] = meta,
            });

            using var msg = new HttpRequestMessage(HttpMethod.Post, _opts.ApiUrl.TrimEnd('/') + "/v1/events")
            {
                Content = new StringContent(body, Encoding.UTF8, "application/json"),
            };
            msg.Headers.TryAddWithoutValidation("Authorization", "Bearer " + _opts.ApiKey);
            msg.Headers.TryAddWithoutValidation("Idempotency-Key", requestId);

            var http = _httpFactory.CreateClient(HttpClientName);
            using var res = await http.SendAsync(msg);
            if (!res.IsSuccessStatusCode)
                _log.LogWarning("[ImmutableLog] event rejected: HTTP {Status}", (int)res.StatusCode);
        }
        catch (Exception ex)
        {
            _log.LogWarning("[ImmutableLog] failed to send event: {Message}", ex.Message);
        }
    }

    private static string? RouteTemplate(Endpoint? endpoint)
    {
        var raw = (endpoint as RouteEndpoint)?.RoutePattern.RawText;
        if (string.IsNullOrEmpty(raw)) return null;
        return raw.StartsWith('/') ? raw : "/" + raw;
    }

    /// <summary>
    /// client_ip for the SIEM: first entry of X-Forwarded-For, then X-Real-IP, then the socket
    /// peer. Only a bare IP is returned (no port): the SIEM drops "ip:port" silently. Headers are
    /// trusted as they come; see "Proxy e X-Forwarded-For" in the README.
    /// </summary>
    internal static string? ClientIp(string xff, string realIp, IPAddress? peer)
    {
        var first = xff.Split(',')[0];
        return BareIp(first) ?? BareIp(realIp) ?? (peer != null ? Canonical(peer).ToString() : null);
    }

    /// <summary>"203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP.</summary>
    private static string? BareIp(string? raw)
    {
        var s = (raw ?? "").Trim();
        if (s.Length == 0) return null;
        string host;
        if (s.StartsWith('['))
        {
            var end = s.IndexOf(']');
            host = end > 0 ? s.Substring(1, end - 1) : "";
        }
        else if (s.Count(c => c == ':') == 1) host = s[..s.IndexOf(':')];
        else host = s;
        // IPAddress.TryParse accepts legacy forms like "12345"; require a real IPv4/IPv6 shape.
        if (!host.Contains('.') && !host.Contains(':')) return null;
        return IPAddress.TryParse(host, out var ip) ? Canonical(ip).ToString() : null;
    }

    /// <summary>"::ffff:10.0.0.1" (Kestrel on a dual-stack socket) -> "10.0.0.1".</summary>
    private static IPAddress Canonical(IPAddress ip) =>
        ip.AddressFamily == AddressFamily.InterNetworkV6 && ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip;

    /// <summary>The core rejects a trail that is empty, longer than 256 chars or contains ':'.</summary>
    private static string? SanitizeTrail(string? v)
    {
        if (v == null) return null;
        var s = v.Trim().Replace(':', '-');
        if (s.Length > MaxTrail) s = s[..MaxTrail];
        return s.Length == 0 ? null : s;
    }

    private static string Truncate(string s, int max) => s.Length > max ? s[..max] : s;
}

public static class ImmutableLogExtensions
{
    /// <summary>Registers the options, the named HttpClient and the middleware.</summary>
    public static IServiceCollection AddImmutableLog(this IServiceCollection services, Action<ImmutableLogOptions>? configure = null)
    {
        var opts = new ImmutableLogOptions();
        configure?.Invoke(opts);
        services.AddSingleton(opts);
        services.AddHttpClient(ImmutableLogMiddleware.HttpClientName, c => c.Timeout = opts.Timeout);
        services.AddSingleton<ImmutableLogMiddleware>();
        return services;
    }

    /// <summary>Adds the middleware to the pipeline. Register it early, before the endpoints.</summary>
    public static IApplicationBuilder UseImmutableLog(this IApplicationBuilder app) =>
        app.UseMiddleware<ImmutableLogMiddleware>();
}

Registration and Configuration

`AddImmutableLog` registers `ImmutableLogOptions` as a singleton, a named `HttpClient` `immutablelog` (timeout from `o.Timeout`) and the middleware. `UseImmutableLog` goes early in the pipeline, before the endpoints. To register by hand: `services.AddSingleton(new ImmutableLogOptions { ... })`, `services.AddHttpClient("immutablelog")`, `services.AddSingleton<ImmutableLogMiddleware>()` and `app.UseMiddleware<ImmutableLogMiddleware>()`.

csharp
// Program.cs
using ImmutableLog;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddImmutableLog(o =>
{
    o.Service = "my-aspnet-service";
    o.Env = builder.Environment.EnvironmentName;
    o.SkipPaths.Add("/metrics");
});

var app = builder.Build();
app.UseImmutableLog();   // cedo no pipeline, antes dos endpoints
app.MapControllers();
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.

How it works

before next(ctx)

Copies method, path, User-Agent, client_ip and, if enabled, the trail header

await next(ctx)

Runs the rest of the pipeline; catches the exception and rethrows it

finally

Reads status, RouteEndpoint, Items and the error, and builds the event, all still on the request thread

Task.Run(SendAsync)

Sends in the background. The HttpContext is never touched after the request

Idempotency-Key

A new GUID per event, equal to meta.request_id. The incoming X-Request-Id is not used, because it comes from the caller and two different events with the same value would be discarded as a duplicate

body

The middleware never reads the request body: no content, no hash

Do not read the HttpContext inside the send Task. The server recycles the context as soon as the request ends, and code that reads it later may return data from another request or fail. That is why the middleware copies everything in the finally, before starting Task.Run.

Custom event and trail

Set `HttpContext.Items[ImmutableLogItems.EventName]` (literal `"imtbl.eventName"`) and `HttpContext.Items[ImmutableLogItems.Trail]` (literal `"imtbl.trail"`) in any controller or endpoint. The middleware reads these values in the `finally`, when it builds the event.

csharp
[ApiController]
public class PaymentsController : ControllerBase
{
    [HttpPost("payments")]
    public IActionResult Create()
    {
        HttpContext.Items[ImmutableLogItems.EventName] = "payment.created";
        HttpContext.Items[ImmutableLogItems.Trail] = "order-7782";
        return StatusCode(201, new { ok = true });
    }
}

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 `HttpContext.Items[ImmutableLogItems.Trail]` in an endpoint. The value goes through `SanitizeTrail` before sending.

csharp
[HttpPost("flows/{id}/run")]
public IActionResult RunFlow(string id)
{
    HttpContext.Items[ImmutableLogItems.Trail] = $"flow-{id}";
    // ... business logic ...
    return Ok(new { status = "ok" });
}

The trail cannot be empty, exceed 256 characters, or contain `:`, and violations return `400 invalid_immutable_trail`. That is why `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#