Accessing the IHostingEnvironment in static main o

2019-04-29 16:46发布

I'm attempting to get configuration values in my static void main of my upgraded Asp.Net Core RC2 application. In the constructor for Startup, I can get IHostingEnvironment injected in, but can't do that in a static method. I'm following 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 and will get there eventually).

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-29 17:24

If you want to store the password for the Https certificate finally in the User Secrets add the following lines in the appropriate sections in Main of Program.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"]);
            })

The user secrets have to be passed in directly, because the configuration of project.json for "userSecretsId" is not yet accessible at this stage.

查看更多
走好不送
3楼-- · 2019-04-29 17:47

After some discussion on aspnetcore.slack.com in the #general channel (May 26,2016 12:25pm), David Fowler said "you can new up the webhostbuilder and call getsetting(“ environment”)" and "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();
查看更多
登录 后发表回答