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

如何在启用Azure Insights追踪的.NET Core API响应头中添加依赖调用统计?

实现方案方向

1. 自定义遥测处理器追踪依赖计数

通过实现ITelemetryProcessor拦截Application Insights的依赖遥测数据,结合IHttpContextAccessor将当前请求的依赖调用次数累计到请求上下文中:

public class DependencyCountTelemetryProcessor : ITelemetryProcessor
{
    private readonly ITelemetryProcessor _nextProcessor;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public DependencyCountTelemetryProcessor(ITelemetryProcessor nextProcessor, IHttpContextAccessor httpContextAccessor)
    {
        _nextProcessor = nextProcessor;
        _httpContextAccessor = httpContextAccessor;
    }

    public void Process(ITelemetry telemetryItem)
    {
        if (telemetryItem is DependencyTelemetry)
        {
            var currentContext = _httpContextAccessor.HttpContext;
            if (currentContext != null)
            {
                currentContext.Items["DependencyCallCount"] = 
                    currentContext.Items.ContainsKey("DependencyCallCount") 
                        ? (int)currentContext.Items["DependencyCallCount"] + 1 
                        : 1;
            }
        }
        _nextProcessor.Process(telemetryItem);
    }
}

在Program.cs中注册处理器和上下文访问器:

builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<ITelemetryProcessor, DependencyCountTelemetryProcessor>();

2. 中间件注入响应头

编写一个中间件,在请求处理完成后从上下文取出计数,添加到HTTP响应头:

public class DependencyCountHeaderMiddleware
{
    private readonly RequestDelegate _next;

    public DependencyCountHeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 先执行后续管道逻辑,处理请求
        await _next(context);

        // 请求处理完成后,添加响应头
        if (context.Items.TryGetValue("DependencyCallCount", out var countObj) && countObj is int count)
        {
            context.Response.Headers.TryAdd("X-Dependency-Call-Count", count.ToString());
        }
    }
}

在Program.cs中注册中间件(建议放在UseAuthorization之后、UseEndpoints之前):

app.UseMiddleware<DependencyCountHeaderMiddleware>();

3. 关键注意事项

  • 过滤无效依赖:如果需要排除特定类型的依赖(比如内部HTTP调用、测试依赖),可在DependencyCountTelemetryProcessor中通过DependencyTelemetry的Type、Name等属性添加过滤逻辑。
  • 线程安全:由于HttpContext.Items是请求级别的隔离存储,即使API中有异步并行调用,计数也能准确对应当前请求。
  • 性能影响:该方案仅做简单的计数和头信息写入,对请求性能的影响可忽略不计。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:41:00