How to Implement API Request Correlation IDs in ASP.NET Core 10 with Serilog
Use a server-generated request ID to find all application log entries for one HTTP request. Keep the W3C trace ID as a separate structured property so operators can follow the request across instrumented services. Serilog’s request middleware adds one completion event with method, path, status and elapsed time.
Choose an identifier for each job
| Identifier | Scope | Typical use |
|---|---|---|
| RequestId | One server request | Support lookup from a response header |
| TraceId | Multiple instrumented services | Find related distributed operations |
| SpanId | One operation in a trace | Identify a specific hop or dependency call |
Do not put raw caller input into a structured correlation field. This lab generates a fresh ID and echoes it to the caller. With a trusted internal gateway, validate and bound any propagated application ID. Keep authentication decisions independent of all three identifiers.
Configure Serilog and request middleware
Add the Serilog.AspNetCore package matching the app’s ASP.NET Core major version. Place the enrichment middleware before UseSerilogRequestLogging so both completion and endpoint logs run inside the same scope. Use a distinct SupportRequestId property to avoid colliding with the framework’s RequestId logging scope. Keep the scope until the asynchronous request finishes. Use an allowlist of fields in your real log sink.
Create an empty ASP.NET Core Web project targeting .NET 10, replace Program.cs, then run the app on loopback. Use these commands from the parent directory.
dotnet new web -n Lab -f net10.0
cd Lab
dotnet add package Serilog.AspNetCore --version 10.0.0
dotnet run --no-launch-profile --urls http://localhost:5080
Program.cs
using System.Diagnostics;
using Serilog;
using Serilog.Context;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSerilog((services, logger) =>
logger.Enrich.FromLogContext().WriteTo.Console(outputTemplate:
"[{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"));
var app = builder.Build();
app.Use(async (context, next) =>
{
var requestId = Guid.NewGuid().ToString("N");
context.TraceIdentifier = requestId;
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Request-Id"] = requestId;
return Task.CompletedTask;
});
using var requestScope = LogContext.PushProperty("SupportRequestId", requestId);
using var traceScope = LogContext.PushProperty("TraceId", Activity.Current?.TraceId.ToHexString());
await next(context);
});
app.UseSerilogRequestLogging();
app.MapGet("/work", (ILoggerFactory factory) =>
{
factory.CreateLogger("Work").LogInformation("Started the sample work item");
return Results.Ok();
});
app.Run();
Verify one request end to end
Start the lab and call curl -i http://localhost:5080/work. Copy X-Request-Id from the response and find that value in both the work event and the completion event. Send a W3C traceparent header from a test client and check that the emitted trace ID matches the upstream trace when the ASP.NET Core activity is active. An unrelated request should get a different request ID.
Instrument outgoing HttpClient calls and preserve W3C propagation across trusted boundaries. Avoid manually copying an incoming traceparent string to every downstream call. An instrumented HTTP client can create the appropriate child activity. If support staff need the ID in a cross-origin browser client, expose X-Request-Id through the CORS policy.
Common questions
Can I use TraceIdentifier as a distributed trace ID? It identifies the local request. Activity.Current supplies the trace ID for distributed correlation.
What should I avoid logging? Authorization headers, cookies, full bodies and unreviewed query strings. Include route templates or stable event names when raw paths can contain sensitive identifiers.
Comments
Post a Comment