@@ -310,17 +310,8 @@ private static void RecordRequestStartEventLog(HttpContext httpContext)
310
310
[ MethodImpl ( MethodImplOptions . NoInlining ) ]
311
311
private Activity ? StartActivity ( HttpContext httpContext , bool loggingEnabled , bool diagnosticListenerActivityCreationEnabled , out bool hasDiagnosticListener )
312
312
{
313
- var activity = _activitySource . CreateActivity ( ActivityName , ActivityKind . Server ) ;
314
- if ( activity is null && ( loggingEnabled || diagnosticListenerActivityCreationEnabled ) )
315
- {
316
- activity = new Activity ( ActivityName ) ;
317
- }
318
313
hasDiagnosticListener = false ;
319
314
320
- if ( activity is null )
321
- {
322
- return null ;
323
- }
324
315
var headers = httpContext . Request . Headers ;
325
316
_propagator . ExtractTraceIdAndState ( headers ,
326
317
static ( object ? carrier , string fieldName , out string ? fieldValue , out IEnumerable < string > ? fieldValues ) =>
@@ -332,9 +323,44 @@ private static void RecordRequestStartEventLog(HttpContext httpContext)
332
323
out var requestId ,
333
324
out var traceState ) ;
334
325
326
+ Activity ? activity = null ;
327
+ if ( _activitySource . HasListeners ( ) )
328
+ {
329
+ if ( ActivityContext . TryParse ( requestId , traceState , true , out ActivityContext context ) )
330
+ {
331
+ // The requestId used W3C ID format. Unfortunately the ActivitySource.CreateActivity overload that
332
+ // takes a string ID sets ActivityContext.IsRemote = false when it parses the string internally.
333
+ // We work around that by using the ActivityContext ID overload and setting ActivityContext.IsRemote
334
+ // to true after parsing it.
335
+ activity = _activitySource . CreateActivity ( ActivityName , ActivityKind . Server , context ) ;
336
+ }
337
+ else
338
+ {
339
+ // Pass in the ID we got from the headers if there was one.
340
+ activity = _activitySource . CreateActivity ( ActivityName , ActivityKind . Server , string . IsNullOrEmpty ( requestId ) ? null ! : requestId ) ;
341
+ }
342
+ }
343
+
344
+ if ( activity is null )
345
+ {
346
+ // CreateActivity didn't create an Activity (this is an optimization for the
347
+ // case when there are no listeners). Let's create it here if needed.
348
+ if ( loggingEnabled || diagnosticListenerActivityCreationEnabled )
349
+ {
350
+ activity = new Activity ( ActivityName ) ;
351
+ if ( ! string . IsNullOrEmpty ( requestId ) )
352
+ {
353
+ activity . SetParentId ( requestId ) ;
354
+ }
355
+ }
356
+ else
357
+ {
358
+ return null ;
359
+ }
360
+ }
361
+
335
362
if ( ! string . IsNullOrEmpty ( requestId ) )
336
363
{
337
- activity . SetParentId ( requestId ) ;
338
364
if ( ! string . IsNullOrEmpty ( traceState ) )
339
365
{
340
366
activity . TraceStateString = traceState ;
0 commit comments