CorrelationId Documentation
repository·main·Indexed 20 days ago
https://github.com/stevejgordon/correlationidA lightweight .NET Standard 2.0+ library for distributed applications to trace requests across multiple services. It manages and propagates correlation IDs via request headers and Correlation Context, providing ICorrelationIdProvider implementations like GuidCorrelationIdProvider and TraceIdCorrelationIdProvider, and an ICorrelationContextAccessor for accessing IDs in business logic or background services.
What's inside CorrelationId
- The Correlation ID library is a lightweight solution for managing request correlation. It allows you to parse a configurable correlation ID header from incoming HTTP requests, access that ID within your application code, and optionally include it in outgoing requests to maintain traceability across distributed systems.
How ICorrelationIdProvider works
mainIn version 3.0.0 and later, the library uses the
ICorrelationIdProviderabstraction to define how correlation IDs are generated. You can choose between different implementations to control the ID generation logic.Two built-in implementations are available:
GuidCorrelationIdProvider: Generates new GUID-based correlation IDs.TraceIdCorrelationIdProvider: Sets the correlation ID to the same value as theHttpContext.TraceIdentifier.
Important: Only one provider may be registered. Registering multiple providers will throw an
InvalidOperationException.// Example of registering a specific provider using the generic AddCorrelationId method services.AddCorrelationId<TraceIdCorrelationIdProvider>();Access CorrelationId via ICorrelationContextAccessor
mainSince version 2.0.0, the library uses a
CorrelationContextto allow access to the Correlation ID in classes that do not have direct access toHttpContext(such as background services or deep business logic layers).You can inject
ICorrelationContextAccessorinto your classes to retrieve the currentCorrelationContextand its associated ID.public class MyService { private readonly ICorrelationContextAccessor _correlationContextAccessor; public MyService(ICorrelationContextAccessor correlationContextAccessor) { _correlationContextAccessor = correlationContextAccessor; } public void DoWork() { var correlationId = _correlationContextAccessor.CorrelationContext.CorrelationId; // Use the ID... } }Register CorrelationId services in ASP.NET Core
mainStarting with version 3.0.0, you must register correlation ID services in your
IServiceCollectionbefore adding the middleware to the pipeline. There are three ways to register services:- Using
AddCorrelationId(): Returns anICorrelationIdBuilder. This method does not set a default provider, so you must call a builder method (like those for specific providers) to configure which provider to use. - Using
AddCorrelationId<T>(): Accepts a typeTthat implementsICorrelationIdProviderto specify the provider directly. - Using
AddDefaultCorrelationId(): Returns theIServiceCollectionand usesGuidCorrelationIdProvideras the default. This is useful for chaining extension methods when the default GUID behavior is sufficient.
// Option 1: Using the builder to configure a provider services.AddCorrelationId() .UseTraceIdCorrelationIdProvider(); // Option 2: Specifying the provider type directly services.AddCorrelationId<GuidCorrelationIdProvider>(); // Option 3: Using the default (GuidCorrelationIdProvider) services.AddDefaultCorrelationId();- Using
Configure CorrelationId with Dependency Injection
mainTo enable the library, register the correlation ID services within your
ConfigureServicesmethod. UsingAddDefaultCorrelationIdregisters a correlation ID provider that generates new IDs based on a random GUID.services.AddDefaultCorrelationIdInstall CorrelationId via NuGet
mainInstall the
CorrelationIdpackage using the NuGet Package Manager Console to include the library and its dependencies in your .NET Standard 2.0+ project.Install-Package CorrelationIdAdd CorrelationId Middleware to the Pipeline
mainRegister the correlation ID middleware in your application pipeline using
app.UseCorrelationId(). This should be registered early in the pipeline, before any downstream middleware that requires access to the correlation ID.app.UseCorrelationId();Configure CorrelationIdOptions
mainIn version 3.0.0 and later,
CorrelationIdOptionsshould be configured via Action delegates on theIServiceCollectionextension methods, rather than passing an options instance toUseCorrelationIdin the middleware pipeline.Common configuration options include:
CorrelationIdGenerator: AFunc<string>used to customize ID generation if no ID is found in the request header. Note that if this is set, it is used instead of the registeredICorrelationIdProvider.RequestHeader: The name of the header to read the correlation ID from (formerlyDefaultHeader).ResponseHeader: The name of the header to which the Correlation ID is written. Defaults to the same value asRequestHeader.IgnoreRequestHeader: Iftrue, the incoming correlation ID in theRequestHeaderis ignored and a new one is generated.EnforceHeader: Iftrue, a missing correlation ID header results in a400 Bad Requestresponse.AddToLoggingScope: Iftrue, the correlation ID is added to the logger scope payload.LoggingScopeKey: The key used in the logger scope (defaults to'CorrelationId').UpdateTraceIdentifier: Controls whether the ASP.NET CoreTraceIdentifieris updated to match theCorrelationId(default istrue).
services.AddDefaultCorrelationId(options => { options.CorrelationIdGenerator = () => "Foo"; options.AddToLoggingScope = true; options.EnforceHeader = true; options.IgnoreRequestHeader = false; options.IncludeInResponse = true; options.RequestHeader = "My-Custom-Correlation-Id"; options.ResponseHeader = "X-Correlation-Id"; options.UpdateTraceIdentifier = false; });Workaround for ASP.NET Core 2.2.0 TraceIdentifier regression
mainIn ASP.NET Core 2.2.0, setting theTraceIdentifieron the context via middleware can cause the context to become null later in the pipeline. If you are using this version, you can work around this by disabling the behavior of updating theTraceIdentifiervia the options when adding the middleware.Access the current Correlation ID using ICorrelationContextAccessor
mainTo retrieve the current correlation ID (for example, for logging purposes), inject the
ICorrelationContextAccessorinto your class via constructor injection.public class TransientClass { private readonly ICorrelationContextAccessor _correlationContext; public TransientClass(ICorrelationContextAccessor correlationContext) { _correlationContext = correlationContext; } // Use _correlationContext to access the ID }Reference: CorrelationIdOptions properties
mainThe following properties are available on
CorrelationIdOptions(as of v3.0.1):Property Type Description CorrelationIdGeneratorFunc<string>Custom generator used if no ID is found in the request header. Overrides ICorrelationIdProvider.RequestHeaderstringThe header name to read the ID from. (Renamed from DefaultHeader).ResponseHeaderstringThe header name to write the ID to. Defaults to RequestHeader.IgnoreRequestHeaderboolIf true, ignores incoming header and generates a new ID.EnforceHeaderboolIf true, returns400 Bad Requestif the header is missing.AddToLoggingScopeboolIf true, adds the ID to the logger scope.LoggingScopeKeystringThe key used in the logger scope. Defaults to 'CorrelationId'.UpdateTraceIdentifierboolIf true, sets ASP.NET CoreTraceIdentifierto match theCorrelationId. Defaults totrue.