访问 ASP.NET Core 的 static main 中的 IHostingEnvironment

Accessing the IHostingEnvironment in static main of ASP.NET Core

我正在尝试在升级后的 Asp.Net 核心 RC2 应用程序的静态无效主体中获取配置值。在 Startup 的构造函数中,我可以注入 IHostingEnvironment,但不能在静态方法中执行此操作。 我正在关注 https://github.com/aspnet/KestrelHttpServer/blob/dev/samples/SampleApp/Startup.cs, but want to have my pfx password in appsettings (yes, it should be in user secrets,最终会到达那里。

public Startup(IHostingEnvironment env){}

public static void Main(string[] args)
{
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddJsonFile("hosting.json");
        builder.AddEnvironmentVariables();
        var configuration = builder.Build();
       ...
       var host = new WebHostBuilder()
            .UseKestrel(options =>
            {
                // options.ThreadCount = 4;
                options.NoDelay = true;
                options.UseHttps(testCertPath, configuration["pfxPassword"]);
                options.UseConnectionLogging();
            })
}

在#general 频道(2016 年 5 月 26 日 12:25pm)对 aspnetcore.slack.com 进行了一些讨论后,David Fowler 说 "you can new up the webhostbuilder and call getsetting(“ environment”)" 和 "hosting config != app config"。

var h = new WebHostBuilder();
var environment = h.GetSetting("environment");
var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{environment}.json", optional: true)
        .AddEnvironmentVariables();
var configuration = builder.Build();

如果你想在 User Secrets 中最终存储 Https 证书的密码,请在 Program.cs 的 Main 中的相应部分添加以下行:

var config = new ConfigurationBuilder()
    .AddUserSecrets("your-user-secrets-id") //usually in project.json

var host = new WebHostBuilder()
    .UseConfiguration(config)
            .UseKestrel(options=> {
                options.UseHttps("certificate.pfx", config["your-user-secrets-id"]);
            })

用户密码必须直接传入,因为 project.json 为 "userSecretsId" 的配置在这个阶段还不能访问。