.NET 4.6.2 WebApi项目添加Application Insights遥测失败如何解决
故障定位
该故障出现在Visual Studio Application Insights集成向导的Azure资源关联后依赖自动拉取、配置注入阶段,触发原因通常包括:VS内置App Insights工具对.NET Framework 4.6.2版本的兼容缺陷、本地NuGet源拉取依赖超时、当前登录VS的Azure账号对目标App Insights资源权限不足、VS的Application Insights扩展版本过旧。
对应操作截图如下:

解决方案
方案1:跳过向导手动配置(推荐,成功率最高)
- 右键项目选择「管理NuGet程序包」,搜索安装
Microsoft.ApplicationInsights.Web稳定版,注意选择2.21.0及以下版本,更高版本不再支持.NET Framework 4.6.2 - 打开项目根目录下的
Web.config文件,在<appSettings>节点中添加配置:
<!-- 填写你Azure Portal中App Insights资源对应的检测密钥 --> <add key="InstrumentationKey" value="xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx" /> <!-- 也可选择使用连接字符串配置,优先级高于检测密钥 --> <add key="APPLICATIONINSIGHTS_CONNECTION_STRING" value="InstrumentationKey=xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx;IngestionEndpoint=https://xxxxxx.applicationinsights.azure.com/" />
- 打开
Global.asax.cs文件,在Application_Start方法中添加初始化代码:
using Microsoft.ApplicationInsights.Extensibility; using System.Configuration; protected void Application_Start(object sender, EventArgs e) { // 其他原有初始化代码 TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings["InstrumentationKey"]; // 如果用连接字符串则替换为下面这行 // TelemetryConfiguration.Active.ConnectionString = ConfigurationManager.AppSettings["APPLICATIONINSIGHTS_CONNECTION_STRING"]; }
- 编译运行项目,即可正常上报遥测数据到对应App Insights资源。
方案2:修复向导后重试
如果需要使用向导完成配置,可按以下步骤排查修复:
- 打开Visual Studio安装程序,更新「Azure开发」工作负载到最新版本,同时检查扩展管理中「Application Insights 工具」是否为最新版,升级后重启VS
- 依次点击VS菜单栏「工具>NuGet包管理器>包管理器设置>常规」,点击「清除所有NuGet缓存」,确保依赖包拉取不受本地缓存异常影响
- 检查当前登录VS的Azure账号,确认对目标App Insights资源拥有至少「参与者」权限
- 关闭本地代理、防火墙软件后重新执行向导操作。
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

