Search code examples
c#asp.net-core-1.0

Accessing the IHostingEnvironment in static main of ASP.NET Core


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();
            })
}

Solution

  • 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.