Accessing the IHostingEnvironment in static main of ASP.NET Core

◇◆丶佛笑我妖孽 提交于 2019-12-07 04:09:45

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/37466195/accessing-the-ihostingenvironment-in-static-main-of-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!