/// <summary> /// Gets the accessor used to retreive a correlation id from an <see cref="HttpContext"/>. /// </summary> /// <param name="httpContext">The http context.</param> /// <returns>The correlation id accessor.</returns> /// <param name="correlationIdHeader">The name of the correlation id header.</param> public static ICorrelationIdAccessor GetCorrelationIdAccessor(this HttpContext httpContext, string correlationIdHeader = CorrelationId) { if (httpContext is null) { throw new ArgumentNullException(nameof(httpContext)); } if (correlationIdHeader is null) { throw new ArgumentNullException(nameof(correlationIdHeader)); } if (!httpContext.Items.TryGetValue(typeof(ICorrelationIdAccessor), out var value) || !(value is ICorrelationIdAccessor accessor)) { accessor = new CorrelationIdAccessor(); if (httpContext.GetHeaderValue(correlationIdHeader) is StringValues correlationId && correlationId.Count > 0) { accessor.CorrelationId = correlationId; } // lean on OpenTelemetry for an existing traceId if (accessor.CorrelationId is null) { accessor.CorrelationId = Tracer.CurrentSpan?.Context.TraceId.ToString(); } // fallback to creating a new value if (accessor.CorrelationId is null) { accessor.CorrelationId = Guid.NewGuid().ToString(); } httpContext.Items[typeof(ICorrelationIdAccessor)] = accessor; } return(accessor); }
public CorrelationIdAccessorTests() { _underTest = new CorrelationIdAccessor(); }