如何手动将跟踪(相关)ID从控制台应用程序传递到ASP.NET核心并影响Activity.current.traceid

发布于 2025-01-30 22:53:23 字数 847 浏览 3 评论 0原文

我正在尝试将“请求-ID”标头从前端(控制台)应用程序传递到后端ASP.NET核心服务(.NET 6),并期望 activity.current.current.traceid 具有相同值的属性。当我指定“ request-iD”标头时,后端上的 activity.current.traceid 将导致一个空的GUID。当我不指定标题时,它会创建一个新的GUID。我在尝试正确的方法吗?

我的实际要求是能够将控制台应用程序中的操作与后端操作相关联。我正在尝试通过允许客户端将自定义跟踪/关联ID传递给后端服务器,然后后端将ID通过后端重新使用。要使用的遥测客户端是Azure应用程序的见解,但是我现在将其禁用以保持简单并简单地观察跟踪ID。

我想念什么?控制台应用程序中的代码看起来像:

HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "/activity/correlationId");
httpRequestMessage.Headers.Add("Request-Id", Activity.Current.TraceId.ToString());

HttpResponseMessage responseMessage = await client.SendAsync(httpRequestMessage);

更新:我已经设法使用W3C格式将请求-ID标头从控制台应用程序传递到后端应用程序,但是现在我很难弄清楚为什么要弄清楚为什么当在后端服务器上使用新的HTTPCLIENT发送请求时,此请求ID不会传播。总而言之,如何在.NET Core中设置HTTPCLIENT以自动注入跟踪上下文标头?

I am trying to pass a "Request-Id" header from a front-end (console) application to a back-end ASP.Net Core service (.NET 6) and expecting the Activity.Current.TraceId property to have the same value. The Activity.Current.TraceId on the back-end is resulting in an empty GUID when I specify the "Request-Id" header. When I don't specify the header, it creates a new GUID. Am I trying the correct approach?

My actual requirement is to be able to correlate operations in the console app with operations in the back-end ones. I am trying to do this by allowing the client to pass a custom trace/correlation ID to the back-end server, and then that ID is re-used by the back-end for all its subsequent operations. The telemetry client to be used is Azure Application Insights, but I disabled it for now to keep things simple and simply observe the trace IDs.

What am I missing? The code in the console app looks like this:

HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "/activity/correlationId");
httpRequestMessage.Headers.Add("Request-Id", Activity.Current.TraceId.ToString());

HttpResponseMessage responseMessage = await client.SendAsync(httpRequestMessage);

UPDATE: I've managed to pass the Request-Id header from the console app to the back-end app using the W3C format, but now I'm having trouble trying to figure out why this request-id won't propagate when sending a request with a new HTTPClient on the back-end server. To summarize, how do I setup HttpClient in .NET Core to automatically inject trace context header?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文