2017-04-18 80 views
0

在我的ASP.NET Core项目中,我依靠命令行参数来覆盖默认url并覆盖环境设置。通过ConfiguratonBuilder获取主机环境?

DOTNET手表运行--server.urls = https://localhost:5001 --environment “本地主机”

我用CommandLineConfigurationExtensions到args添加到ConfigurationBuilder。这工作得很好,但我也想使用内置配置

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     var configuration = new ConfigurationBuilder() 
      .AddCommandLine(args) 
      .Build(); 

     // More stuff happens with WebHostBuilder, 
     // and I would very much like to check the 
     // environment here. 
    } 
} 

我想访问相同的环境设置,都可以通过在Startup类的Configure()方法IHostingEnvironment env参数。但我想这样做在Main()

我意识到我可以只是解析命令行参数,并寻找自己的值,或从configuration可变我刚刚建立拉适当的值。然而,当在框架的任何部分中神奇地实例化实现我们其他人使用的接口的类时,显然存在一种标准化的方法似乎不太合适。

回答

1

您可以直接使用config["environment"]或者如果没有指定,则将Hosting.EnvironmentName.Production设置为默认值。

让我解释一下为什么。

如果你看看IHostingEnvironmentimplementation,你会看到EnvironmentName是一个简单的属性与公共的getter/setter,默认情况下,它包含了Production值:

public class HostingEnvironment : IHostingEnvironment 
{ 
    public string EnvironmentName { get; set; } = Hosting.EnvironmentName.Production; 
    ... 
} 

然后值可以改变时Initializeextension method叫做。从WebHostOptions option使用数据:

hostingEnvironment.EnvironmentName = 
    options.Environment ?? 
    hostingEnvironment.EnvironmentName; 

更具体地讲,在option.Environment财产is used,即

public WebHostOptions(IConfiguration configuration) 
{ 
    ... 
    Environment = configuration[WebHostDefaults.EnvironmentKey]; 
    ... 
} 

其中WebHostDefaults.EnvironmentKey

public static class WebHostDefaults 
{ 
    public static readonly string EnvironmentKey = "environment"; 
} 

所以environment密钥从配置源用于指定主机环境。

+0

只要'config [“environment”]'“合并”来设置当前环境,我很高兴使用它。感谢您的洞察!它为我提供了非常需要的信心:) –