访问ASP.NET Core静态主中的IHostingEnvironment

Ali*_*ned 5 c# asp.net-core-1.0

我正在尝试在我升级的Asp.Net Core RC2应用程序的静态void main中获取配置值.在Startup的构造函数中,我可以注入IHostingEnvironment,但不能在静态方法中执行此操作.我正在关注https://github.com/aspnet/KestrelHttpServer/blob/dev/samples/SampleApp/Startup.cs,但想在appsettings中使用我的pfx密码(是的,它应该在用户机密中并且会到达那里最终).

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();
            })
}
Run Code Online (Sandbox Code Playgroud)

Ali*_*ned 17

在#general频道(2016年5月26日下午12:25)对aspnetcore.slack.com进行一些讨论之后,David Fowler说"你可以新建webhostbuilder并调用getsetting("environment")"和"hosting config!= app配置".

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();
Run Code Online (Sandbox Code Playgroud)


pis*_*ker 3

如果您希望最终将 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"]);
            })
Run Code Online (Sandbox Code Playgroud)

用户机密必须直接传入,因为现阶段还无法访问“userSecretsId”的project.json 配置。