如何设置环境名称(IHostingEnvironment.EnvironmentName)?

tsd*_*mon 64 c# asp.net asp.net-core

默认的ASP.NET Core Web项目包含以下行Startup.cs:

if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
    app.UseBrowserLink();
    app.UseDeveloperExceptionPage(ErrorPageOptions.ShowAll);
}
else
{
    app.UseExceptionHandler("/Home/Error");
}
Run Code Online (Sandbox Code Playgroud)

据我了解,EnvironmentName是一种处理开发/生产环境的新方法.但它在发布版本配置上没有变化.那么设置不同的方法是什么EnvironmentName

我可以想象它应该在"命令"中设置为服务器的参数.

Sha*_*tin 75

RC2之后

那么设置不同的EnvironmentName的方法是什么?

设置ASPNETCORE_ENVIRONMENT环境变量.

设置该环境变量的方法有很多种.这些包括launchSettings.json配置文件和其他特定于环境的方式.这里有些例子.

从控制台:

// PowerShell
> $env:ASPNETCORE_ENVIRONMENT="Development"

// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development

// Bash
> ASPNETCORE_ENVIRONMENT=Development
Run Code Online (Sandbox Code Playgroud)

从Azure Web App的应用程序设置:

在Azure中设置环境名称

在RC2之前

我可以想象它应该在"命令"中设置为服务器的参数.

那是真实的.在project.json中,添加--ASPNET_ENV production为服务器的参数.

"commands": {
  "web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
}
Run Code Online (Sandbox Code Playgroud)

现在当你从命令行运行时dnx . web,ASPNET_ENV将会是production.

相关的ASP.NET核心托管源代码

WebHostBuilder联合收割机"ASPNETCORE_"WebHostDefaults.EnvironmentKey制作"ASPNETCORE_environment".它还支持传统密钥.

WebHostDefaults.cs

namespace Microsoft.AspNetCore.Hosting
{
    public static class WebHostDefaults
    {
        public static readonly string ApplicationKey = "applicationName";
        public static readonly string StartupAssemblyKey = "startupAssembly";

        public static readonly string DetailedErrorsKey = "detailedErrors";
        public static readonly string EnvironmentKey = "environment";
        public static readonly string WebRootKey = "webroot";
        public static readonly string CaptureStartupErrorsKey = "captureStartupErrors";
        public static readonly string ServerUrlsKey = "urls";
        public static readonly string ContentRootKey = "contentRoot";
    }
}
Run Code Online (Sandbox Code Playgroud)

WebHostBuilder.cs

_config = new ConfigurationBuilder()
    .AddEnvironmentVariables(prefix: "ASPNETCORE_")
    .Build();

if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey)))
{
    // Try adding legacy environment keys, never remove these.
    UseSetting(WebHostDefaults.EnvironmentKey, 
        Environment.GetEnvironmentVariable("Hosting:Environment") 
        ?? Environment.GetEnvironmentVariable("ASPNET_ENV"));
}
Run Code Online (Sandbox Code Playgroud)

向后兼容性

环境密钥使用ASPNETCORE_ENVIRONMENT环境变量设置.ASPNET_ENV并且Hosting:Environment仍受支持,但会生成已弃用的消息警告.

https://docs.asp.net/en/latest/migration/rc1-to-rtm.html

默认值

默认值为"生产" 并在此处设置.

  • 这是错误的方法,您不需要更改源代码来设置环境变量.请参阅http://docs.asp.net/en/latest/fundamentals/diagnostics.html for visual studio 2015.在Azure上,您设置通过PS或门户网站上的应用程序设置页面的环境变量.@Victor Hurdugaci在下面有正确的答案. (4认同)
  • @RickAnd-MSFT 我不确定我的回答与您的任何建议有何不同。首先,我的回答不会更改源代码,除非您指的是 `project.json` 文件,我不认为它是源代码。其次,在 Azure 上,我的回答建议使用门户中的应用程序设置来设置变量,这也是您的建议。您关于使用 Visual Studio 的建议在 Windows 上可能没问题,但不适用于 Mac 或 Linux 上的用户,他们无法使用 Visual Studio 2015,并且可能正在使用 Visual Studio Code 或其他文本编辑器。如果我错了,请纠正我。 (3认同)
  • @RickAnd-MSFT 我对此持开放态度,尽管目前我没有被说服。虽然很难找到权威答案,但 NuGet 文档 (https://docs.nuget.org/create/configuration-file-and-source-code-transformations) 的一部分将配置文件与源代码区分开来。另一方面,这个 ASP.NET 教程(http://www.asp.net/identity/overview/features-api/best-practices-for-deploying-passwords-and-other-sensitive-data-to-aspnet -and-azure) 清楚地说明“web.config 是源代码。” (2认同)
  • @RickAnd-MSFT 无论配置文件是否被视为源代码,将环境变量传递给“dnx”似乎都是合适的,因为“dnx”是.NET执行环境。当我们启动环境时,将环境变量传递给它似乎是合适的。 (2认同)

Vic*_*aci 16

您可以通过定义名为的环境变量来设置环境ASPNET_ENV.例如,如果您想要发布SET ASPNET_ENV=Release.

如果您将ASPNET_ENV=Release参数传递给命令但我现在无法检查它也可能有效.

以下是它的实现方式:https://github.com/aspnet/Hosting/blob/217f9ca3d3ccf59ea06e6555820974ba9c3b5932/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs

  • @WillHuang只是将它们添加为Azure Web App上的AppSettings,它们也将作为环境变量添加. (2认同)

cla*_* wu 16

launchsettings.json

在Properties> launchsettings.json

像这样:

    {
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1032/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "WebAppNetCore": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "web": {
      "commandName": "web",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 目前还不清楚代码应该如何知道在部署应用程序时要使用哪个配置文件,因此必须缺少一个由于某种原因没有人愿意共享的内容. (26认同)
  • launchSettings.json仅适用于Visual Studio:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/environments (2认同)
  • 几年后,它仍然可能令人困惑,因为即使按照此处许多响应中描述的所有设置,当在 web.config 中更改/设置 ASPNETCORE_ENVIRONMENT 时,您也会遇到问题。这里有好文章:https://procodeguide.com/programming/asp-net-core-hosting-environment/ (2认同)

Chr*_*nco 7

我有同样的问题.为了独立于环境变量和web.config,我创建了一个.json文件(我称之为envsettings.json):

{
  // Possible string values reported below.
  // - Production
  // - Staging
  // - Development
  "ASPNETCORE_ENVIRONMENT": "Staging"
}
Run Code Online (Sandbox Code Playgroud)

然后在Program.cs中我添加了:

public class Program
{
    public static void Main(string[] args)
    {
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var webHostBuilder = new WebHostBuilder()
            .UseKestrel()
            .CaptureStartupErrors(true)
            .UseSetting("detailedErrors", "true")
            .UseContentRoot(currentDirectoryPath)
            .UseIISIntegration()
            .UseStartup<Startup>();

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(enviromentValue)) 
        {
            webHostBuilder.UseEnvironment(enviromentValue);
        }

        var host = webHostBuilder.Build();

        host.Run();
    }
}
Run Code Online (Sandbox Code Playgroud)


Eve*_*req 6

如果您喜欢使用VS功能(例如VS 2017),则可以在项目属性的“调试”选项卡中添加环境变量。例如,在最新的ASP.NET Core版本(RC2之后)上,应设置ASPNETCORE_ENVIRONMENT变量。

在此处输入图片说明

结果,launchSettings.json将在相应项目的Properties文件夹中创建(或更新)该文件,因此可以轻松地将该文件持久化到您的源代码管理解决方案中并在开发人员之间共享(与使用SET/ SETX命令的其他解决方案相反)

注意:默认情况下,最新的ASP.NET Core将环境设置为生产。所以,你只需要设置ASPNETCORE_ENVIRONMENTDevelopment在VS的调试(见上面的截图)。并且可以肯定的是,当您想在Staging环境中本地运行代码时,应将设置ASPNETCORE_ENVIRONMENTStaging。最后,当您想在生产环境中运行它时,只需删除此变量或将值设置为即可Production

总结一下:只要确保在“调试”对话框中使用了DevelopmentStagingProduction值(而不是'Dev'或其他任何值)来设置环境并使不同的扩展正常工作。

另请参阅来自ASP.NET Core的相关源代码:

namespace Microsoft.AspNetCore.Hosting
{
  /// <summary>Commonly used environment names.</summary>
  public static class EnvironmentName
  {
    public static readonly string Development = "Development";
    public static readonly string Staging = "Staging";
    public static readonly string Production = "Production";
  }
}

namespace Microsoft.AspNetCore.Hosting
{
  /// <summary>
  /// Extension methods for <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.
  /// </summary>
  public static class HostingEnvironmentExtensions
  {
    /// <summary>
    /// Checks if the current hosting environment name is "Development".
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <returns>True if the environment name is "Development", otherwise false.</returns>
    public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return hostingEnvironment.IsEnvironment(EnvironmentName.Development);
    }

    /// <summary>
    /// Checks if the current hosting environment name is "Staging".
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <returns>True if the environment name is "Staging", otherwise false.</returns>
    public static bool IsStaging(this IHostingEnvironment hostingEnvironment)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return hostingEnvironment.IsEnvironment(EnvironmentName.Staging);
    }

    /// <summary>
    /// Checks if the current hosting environment name is "Production".
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <returns>True if the environment name is "Production", otherwise false.</returns>
    public static bool IsProduction(this IHostingEnvironment hostingEnvironment)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return hostingEnvironment.IsEnvironment(EnvironmentName.Production);
    }

    /// <summary>
    /// Compares the current hosting environment name against the specified value.
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <param name="environmentName">Environment name to validate against.</param>
    /// <returns>True if the specified name is the same as the current environment, otherwise false.</returns>
    public static bool IsEnvironment(this IHostingEnvironment hostingEnvironment, string environmentName)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return string.Equals(hostingEnvironment.EnvironmentName, environmentName, StringComparison.OrdinalIgnoreCase);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)