基于.NET 4.6.1的Web API如何在Application Insights中记录所有请求
.NET Framework Web API 自动上报Application Insights请求配置步骤
- 安装必备NuGet包
需安装两个官方适配包,确保自动请求跟踪功能正常启用:Microsoft.ApplicationInsights.Web:负责ASP.NET平台入站请求的自动收集Microsoft.ApplicationInsights.WebApi:专门适配Web API框架,自动采集控制器、动作、路由等请求元数据
推荐使用2.21.x及以上的稳定版,保证和.NET Framework 4.6.1兼容。
- 验证web.config跟踪模块注册
安装上述包后会自动注入跟踪模块,若未自动生成需手动补充配置:
在system.web节点下添加:
在<httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules>system.webServer节点下添加:<modules runAllManagedModulesForAllRequests="true"> <remove name="ApplicationInsightsWebTracking" /> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /> </modules> - 补充Web API适配配置
在WebApiConfig.Register方法中添加扩展方法启用Web API专属跟踪:public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Services.Add(typeof(IExceptionLogger), new InsightsExceptionLogger()); // 新增以下行 config.EnableApplicationInsights(); } - 确认无跟踪禁用配置
检查以下配置是否存在,若存在需删除或调整:TelemetryConfiguration.Active.DisableTelemetry = true全局禁用遥测- ApplicationInsights.config中配置的采样规则过滤了100%的请求
- InstrumentationKey配置为空或无效
本地调试时可在Application_Start中添加TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;,关闭遥测本地缓存,立刻上报数据方便验证。
内容的提问来源于stack exchange,提问作者Matt W
相关产品推荐
相关产品推荐

