.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); }
三、验证数据上报
- 启动应用并触发对应控制器逻辑
- 等待5-10分钟(Application Insights存在数据延迟),在Azure门户中:
- 查看自定义事件:在「日志」中执行查询
customEvents | where name == "CustomEvent_UserID" - 查看自定义指标:在「指标」面板选择
CustomMetricID或TestMetric - 验证默认数据:执行查询
requests | take 10,确认请求数据正常上报且user_Id字段正确
- 查看自定义事件:在「日志」中执行查询
四、常见排查点
- 确认
appsettings.json中APPLICATIONINSIGHTS_CONNECTION_STRING配置正确 - 使用最新版本的
Microsoft.ApplicationInsights.AspNetCoreNuGet包 - 开发环境下查看控制台输出,确认遥测数据是否被SDK正常捕获
内容的提问来源于stack exchange,提问作者Vikram R
相关产品推荐
相关产品推荐

