C# 仅在版本中启用ApplicationInsights

C# 仅在版本中启用ApplicationInsights,c#,razor,asp.net-core,azure-application-insights,C#,Razor,Asp.net Core,Azure Application Insights,在我的ASP.NET核心应用程序中,我只想为发布/生产启用ApplicationInsights。为了实现这一点,我需要有条件地使用三行代码。前两个是`_layout.cshtml的一部分 #if DEBUG #else @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet @* does not work this way *@ #endif <!DOCTYPE html&

在我的ASP.NET核心应用程序中,我只想为发布/生产启用ApplicationInsights。为了实现这一点,我需要有条件地使用三行代码。前两个是`_layout.cshtml的一部分

#if DEBUG
#else
@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet @* does not work this way *@
#endif
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>@ViewData["Title"]</title>
    <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" />
#if DEBUG
#else
@Html.Raw(JavaScriptSnippet.FullScript) @* does not work this way *@
#endif
</head>

<body style='font-family:"-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;"'>
    @await Component.InvokeAsync(typeof(Bsoft.Core.Mvc.BannerViewComponent))
    @RenderBody()

    @RenderSection("scripts", required: false)

</body>
</html>

对于
.UseApplicationInsights()
我可以使用#ifndef DEBUG,但是我如何在仅发行版中应用
\u layout.cshtml
中的更改呢?

您是否可以读取环境变量或配置,并使用它来确定是否调用
@Html.Raw(JavaScriptSnippet.FullScript)
.UseApplicationInsights
使用#ifndef DEBUG即可轻松完成。但是我也需要去掉Razor中的其他部分(否则我的端到端测试不会运行)在
JavaScriptSnippet.FullScript
部分周围添加
#if
,也将其留空以供调试。请注意,在这里使用条件编译(#if)似乎不太正确,因为环境类型是由环境变量提供的(可以通过
IHostingEnvironment
访问,如
environment.IsProduction()
等)。@Sam我不建议更改此设置。我建议围绕此类创建您自己的包装。此包装将检查容器中是否注册了real
JavaScriptSnipper
(当您调用
UseApplicationInsights
时会发生这种情况)如果是,则-将调用其
FullScript
来提供脚本。否则将只提供空字符串。然后将该包装器而不是
JavaScriptSnipper
插入到视图中。您是否可以读取环境变量或配置,并使用它来确定是否调用
@Html.Raw(JavaScriptSnippet.FullScript)
还是不?正如我在问题中所写,
.UseApplicationInsights
可以通过使用#ifndef DEBUG轻松完成。但我也需要去掉Razor中的其他部分(否则我的端到端测试不会运行)在
JavaScriptSnippet.FullScript
部分周围添加
#if
,将其留空以供调试。注意,在这里使用条件编译(#if)似乎不太正确,因为环境类型是由环境变量提供的(可以通过
IHostingEnvironment
访问,如
environment.IsProduction()
etc)。@Sam我不建议更改此设置。我建议围绕此类创建您自己的包装器。此包装器将检查容器中是否注册了real
JavaScriptSnipper
(当您调用
UseApplicationInsights
时会发生这种情况)如果是-将调用其
FullScript
来提供脚本。否则将只提供空字符串。然后将该包装器而不是
JavaScriptSnipper
注入到视图中。
public class Program
{
  public static void Main(string[] args)
  {
    var host = BuildWebHost(args);
    host.Run();
  }

  public static IWebHost BuildWebHost(string[] args)
  {
    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables(prefix: "ASPNETCORE_")
        .Build();
    return new WebHostBuilder()
      .UseConfiguration(config)
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseIISIntegration()
      .UseStartup<Startup>()
#if DEBUG
#else
      .UseApplicationInsights() // <= only in release/production 
#endif
      .Build();
  }
}