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

.NET 4.8+Startup.cs项目Application Insights配置求助

在无global.asax的.NET 4.8+AspNetCore 2.1.7项目中启用Application Insights的解决方案

1. 安装适配的NuGet包

先安装和AspNetCore 2.1.7兼容的Application Insights SDK包,打开NuGet包管理器控制台执行:

Install-Package Microsoft.ApplicationInsights.AspNetCore -Version 2.12.0

这个版本和你的项目框架版本匹配度最高,能避免版本冲突问题。

2. 在App.Config中配置检测密钥

你的项目只有App.Config,直接在<configuration>节点下添加配置(如果已有<appSettings>节点,直接追加条目即可):

<configuration>
  <appSettings>
    <add key="ApplicationInsights:InstrumentationKey" value="你的检测密钥" />
    <!-- 若存在这条禁用配置,删除或设为false -->
    <!-- <add key="ApplicationInsights:DisableTelemetry" value="true" /> -->
  </appSettings>
  <!-- 保留原有其他配置 -->
</configuration>

3. 在Startup.cs中配置Application Insights

第一步:让Configuration读取App.Config内容

修改Startup构造函数,配置读取App.Config的逻辑:

using Microsoft.Extensions.Configuration;
using System.IO;

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddXmlFile("App.Config", optional: false, reloadOnChange: true);
        Configuration = builder.Build();
    }

    // 其他方法...
}

第二步:启用Application Insights遥测

在ConfigureServices方法中添加遥测服务配置:

public void ConfigureServices(IServiceCollection services)
{
    // 启用Application Insights遥测
    services.AddApplicationInsightsTelemetry(Configuration);
    
    // 可选:开启调试日志,方便排查问题
    // services.AddApplicationInsightsTelemetry(options =>
    // {
    //     options.EnableDebugLogger = true;
    // });

    // 保留原有服务配置(比如AddMvc等)
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

4. 验证本地遥测数据

  • 打开Visual Studio的Application Insights工具窗口(通过顶部菜单「视图」→「其他窗口」找到),选择对应的Azure资源和订阅。
  • 本地启动API,用Postman调用接口后,等待1-2分钟(本地遥测存在轻微延迟),就能在工具窗口看到请求和遥测数据。
  • 若仍无数据,打开Visual Studio的输出窗口,选择「显示输出来自:Application Insights Telemetry」,检查是否有发送失败的日志(比如密钥错误、网络拦截等)。

常见排查点

  • 确认检测密钥复制完全正确,无拼写或格式错误。
  • 检查App.Config中是否存在ApplicationInsights:DisableTelemetry设为true的配置,如有则改为false。
  • 本地调试时关闭可能拦截遥测请求的代理或防火墙。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:45:57