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

.NET Core MVC中无法向Application Insights发送自定义指标与事件

解决.NET Core MVC中Application Insights自定义用户ID上报及默认数据恢复问题

一、先修复默认数据停止上报的问题

  • 删除手动Flush()调用:Web应用中Application Insights SDK会自动批量处理并发送遥测数据,你在finally里调用的telemetryClient.Flush()会强制终止当前遥测队列,打断默认数据的正常上报流程,直接删除这行代码即可。
  • 确认TelemetryClient注入正确性:必须通过依赖注入获取TelemetryClient实例,禁止手动new TelemetryClient(),否则会与SDK默认实例冲突。
    配置注入(以.NET 6+为例,在Program.cs中):
    builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);
    
    控制器构造函数注入:
    private readonly TelemetryClient _telemetryClient;
    public YourController(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }
    

二、正确上报用户ID及自定义数据

1. 全局统一设置用户ID(推荐方案)

通过TelemetryInitializer实现所有遥测(包括默认请求、异常)自动携带用户ID,无需在每个控制器重复编码:

public class UserIdTelemetryInitializer : ITelemetryInitializer
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserIdTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        var httpContext = _httpContextAccessor.HttpContext;
        if (httpContext == null || !string.IsNullOrEmpty(telemetry.Context.User.Id))
            return;

        // 从当前上下文获取用户ID,示例从Claims获取,可根据实际逻辑调整
        var userId = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "AnonymousUser";
        telemetry.Context.User.Id = userId;
    }
}

在Program.cs中注册初始化器:

builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<ITelemetryInitializer, UserIdTelemetryInitializer>();

2. 控制器内上报自定义指标与事件

调整你的测试代码,移除Flush(),使用注入的实例:

try
{
    // 上报自定义指标
    _telemetryClient.GetMetric("CustomMetricID").TrackValue(userid);
    _telemetryClient.GetMetric("TestMetric").TrackValue(1);

    // 上报自定义事件
    var customEvent = new EventTelemetry("CustomEvent_UserID");
    customEvent.Properties.Add("Int_USER_ID", userid.ToString());
    customEvent.Properties.Add("Desc", "Working...");
    _telemetryClient.TrackEvent(customEvent);
}
catch (Exception ex)
{
    _telemetryClient.TrackException(ex);
}

三、验证数据上报

  1. 启动应用并触发对应控制器逻辑
  2. 等待5-10分钟(Application Insights存在数据延迟),在Azure门户中:
    • 查看自定义事件:在「日志」中执行查询 customEvents | where name == "CustomEvent_UserID"
    • 查看自定义指标:在「指标」面板选择CustomMetricID或TestMetric
    • 验证默认数据:执行查询 requests | take 10,确认请求数据正常上报且user_Id字段正确

四、常见排查点

  • 确认appsettings.json中APPLICATIONINSIGHTS_CONNECTION_STRING配置正确
  • 使用最新版本的Microsoft.ApplicationInsights.AspNetCore NuGet包
  • 开发环境下查看控制台输出,确认遥测数据是否被SDK正常捕获

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:45:22