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

Azure构建管道生成Web API Swagger文档遇InstrumentationKey缺失错误

问题:生成OpenAPI定义时遇Application Insights连接字符串错误

在Terraform的YAML构建管道中配置了DotNetCoreCLI@2任务用于生成OpenAPI定义,任务配置如下:

- task: DotNetCoreCLI@2
  displayName: 'Generate OpenAPI definition for ${{ parameters.DocumentName }}'
  inputs:
    command: 'custom'
    custom: 'swagger'
    arguments: 'tofile --output $(System.DefaultWorkingDirectory)\openapi_specs\${{ parameters.ApiFileName }} $(System.DefaultWorkingDirectory)\unzipped_artifact\$(ApiStartupName) ${{ parameters.DocumentName }}'

执行任务时抛出以下错误:

Unhandled exception. System.ArgumentException: Connection String Invalid: InstrumentationKey is required.

完整错误栈追踪:

C:\hostedtoolcache\windows\dotnet\dotnet.exe swagger tofile --output D:\a\1\s\openapi_specs\swagger.json D:\a\1\s\unzipped_artifact\Returns.API.dll v1
Unhandled exception. System.ArgumentException: Connection String Invalid: InstrumentationKey is required.
   at Microsoft.ApplicationInsights.Extensibility.Implementation.Endpoints.EndpointProvider.GetInstrumentationKey()
   at Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.set_ConnectionString(String value)
   at Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.SelectInstrumentationKey(TelemetryConfiguration configuration)
   at Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.Initialize(TelemetryConfiguration configuration, TelemetryModules modules, String serializedConfiguration)
   at Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.Initialize(TelemetryConfiguration configuration, TelemetryModules modules)
   at Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault()
   at Microsoft.Extensions.DependencyInjection.TelemetryConfigurationOptions..ctor(IEnumerable`1 configureOptions, IOptions`1 applicationInsightsServiceOptions)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
   at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)

该构建管道此前运行正常,需分析问题原因并给出解决建议。


原因分析

  1. dotnet swagger tofile命令执行时,会加载目标API程序集(此处为Returns.API.dll)并初始化其依赖的服务容器,其中包含Application Insights的配置逻辑。
  2. 程序集初始化阶段尝试读取Application Insights的连接字符串,但当前构建环境中未提供有效的InstrumentationKey,导致配置初始化失败抛出异常。
  3. 管道之前正常运行,大概率是近期API代码新增了Application Insights集成,或是构建环境中存储的相关配置变量被移除、修改。

解决建议

方案1:构建任务中注入临时Application Insights配置

在DotNetCoreCLI@2任务中添加环境变量,提供占位符形式的InstrumentationKey(生成Swagger时无需实际发送遥测数据,占位符即可满足初始化要求):

- task: DotNetCoreCLI@2
  displayName: 'Generate OpenAPI definition for ${{ parameters.DocumentName }}'
  inputs:
    command: 'custom'
    custom: 'swagger'
    arguments: 'tofile --output $(System.DefaultWorkingDirectory)\openapi_specs\${{ parameters.ApiFileName }} $(System.DefaultWorkingDirectory)\unzipped_artifact\$(ApiStartupName) ${{ parameters.DocumentName }}'
  env:
    APPLICATIONINSIGHTS_CONNECTION_STRING: "InstrumentationKey=00000000-0000-0000-0000-000000000000"

方案2:代码层面隔离Swagger生成场景

修改API的Program.cs/Startup.cs,判断当前是否为Swagger生成场景,跳过Application Insights的初始化:

var isSwaggerGeneration = Environment.GetEnvironmentVariable("SWAGGER_GENERATION") == "true";
if (!isSwaggerGeneration)
{
    builder.Services.AddApplicationInsightsTelemetry();
}

然后在构建任务中添加对应的环境变量标记:

- task: DotNetCoreCLI@2
  displayName: 'Generate OpenAPI definition for ${{ parameters.DocumentName }}'
  inputs:
    command: 'custom'
    custom: 'swagger'
    arguments: 'tofile --output $(System.DefaultWorkingDirectory)\openapi_specs\${{ parameters.ApiFileName }} $(System.DefaultWorkingDirectory)\unzipped_artifact\$(ApiStartupName) ${{ parameters.DocumentName }}'
  env:
    SWAGGER_GENERATION: "true"

方案3:使用专用配置文件

为Swagger生成场景创建单独的配置文件appsettings.Swagger.json,配置空的Application Insights连接字符串:

{
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
  }
}

然后在构建任务中指定使用该配置:

- task: DotNetCoreCLI@2
  displayName: 'Generate OpenAPI definition for ${{ parameters.DocumentName }}'
  inputs:
    command: 'custom'
    custom: 'swagger'
    arguments: 'tofile --output $(System.DefaultWorkingDirectory)\openapi_specs\${{ parameters.ApiFileName }} $(System.DefaultWorkingDirectory)\unzipped_artifact\$(ApiStartupName) ${{ parameters.DocumentName }} --configuration Swagger'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:29:51