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

时间:2016-05-26 16:18:30

标签: 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密码(是的,它应该在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();
            })
}

2 个答案:

答案 0 :(得分:14)

在#general频道(2016年5月26日下午12:25)对aspnetcore.slack.com进行一些讨论之后,David Fowler说“你可以新建webhostbuilder并调用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();

答案 1 :(得分:2)

如果您想最终在用户秘密中存储Https证书的密码,请在Main.cite.cs的相应部分添加以下行:

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"现阶段还无法访问。