1

I Found that configuration of ApplicationInsights.InstrumentationKey is not get from User Secrets. In DefaultApplicationInsightsServiceConfigureOptions I found this code:

configBuilder.AddJsonFile("appsettings.json", true)
             .AddJsonFile(string.Format(CultureInfo.InvariantCulture, "appsettings.{0}.json", this.hostingEnvironment.EnvironmentName), true)
             .AddEnvironmentVariables();

so no configuration is get from User Secrets neither from command line arguments.

Is this made on purpose?

Peter Bons
  • 26,826
  • 4
  • 50
  • 74
Lubos
  • 125
  • 2
  • 10

1 Answers1

2

Just because there is a default doesn't mean you cannot store the key as a user secret for example. It is even questionable whether it is a secret at all. If the key is compromised the only risk is that it is used to send additional telemetry. It can't be used for reading telemetry.

That said, you can alter the configuration:

If you want to store the instrumentation key in ASP.NET Core user secrets or retrieve it from another configuration provider, you can use the overload with a Microsoft.Extensions.Configuration.IConfiguration parameter. For example, services.AddApplicationInsightsTelemetry(Configuration);. Starting from Microsoft.ApplicationInsights.AspNetCore version 2.15.0, calling services.AddApplicationInsightsTelemetry() will automatically read the instrumentation key from Microsoft.Extensions.Configuration.IConfiguration of the application. There is no need to explicitly provide the IConfiguration.

(source)

Also, from the same docs, environment variables will do as well:

An instrumentation key specified in code wins over the environment variable APPINSIGHTS_INSTRUMENTATIONKEY, which wins over other options.

Peter Bons
  • 26,826
  • 4
  • 50
  • 74
  • Thanks @peter-bons, use of `services.AddApplicationInsightsTelemetry(Configuration)` solved my case. _...calling services.AddApplicationInsightsTelemetry() will automatically read the instrumentation key from IConfiguration of the application. There is no need to explicitly provide the IConfiguration._ This is not completely true for ASP.NET Core 3.1. This method uses `DefaultApplicationInsightsServiceConfigureOptions` as I mentioned and that doesn't use IConfiguration. It creates it's own from appsettings and environment variables. – Lubos Dec 04 '20 at 07:59
  • Github source of mentioned class: [DefaultApplicationInsightsServiceConfigureOptions.cs](https://github.com/microsoft/ApplicationInsights-dotnet/blob/master/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/DefaultApplicationInsightsServiceConfigureOptions.cs) – Lubos Dec 04 '20 at 08:02