You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中使用OpenTelemetry.Baggage API实现跨微服务Baggage传播问题

解决方案

1. 修正代码执行顺序

你当前的代码先发起了对Matrix服务的HTTP请求,之后才设置Baggage,请求发送时Baggage还未创建,自然不会被携带到下游。调整顺序为先设置Baggage,再发起请求:

// 先将自定义键值对写入当前Baggage上下文
Baggage.Current.SetBaggage("weatherforecastid", "abced123");
// 再发起HTTP调用,instrumentation会自动将Baggage注入请求头
var res = HttpClient.GetStringAsync("http://localhost:5002/Matrix").Result;

2. 全局配置OpenTelemetry传播器

所有链路中的服务都需要显式配置支持W3C Baggage传播,默认传播器仅处理链路追踪上下文,不会携带Baggage:

services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddAspNetCore()
        // 启用HttpClient instrumentation,自动注入/提取链路信息和Baggage
        .AddHttpClientInstrumentation()
        .AddJaegerExporter()
    )
    // 配置组合传播器,同时支持链路上下文和Baggage传播
    .SetTextMapPropagator(new CompositeTextMapPropagator(new List<TextMapPropagator>
    {
        new TraceContextPropagator(),
        new BaggagePropagator()
    }));

3. 下游服务Baggage读取

完成上述配置后,下游Matrix服务及后续调用的其他服务会自动从请求头中提取Baggage存入当前上下文,直接调用以下代码即可读取:

var forecastId = Baggage.Current.GetBaggage("weatherforecastid");

后续该服务发起新的上游调用时,Baggage会被自动继续传递。

注意:.NET中Baggage基于AsyncLocal实现,异步场景下避免使用ConfigureAwait(false)丢失上下文即可保证正常传递。

内容的提问来源于stack exchange,提问作者kharlezaizen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 10:00:01