【问题标题】:Accessing the IHostingEnvironment in static main of ASP.NET Core在 ASP.NET Core 的 static main 中访问 IHostingEnvironment
【发布时间】:2019-07-05 18:03:50
【问题描述】:

我正在尝试在升级后的 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();
            })
}

【问题讨论】:

    标签: c# asp.net-core-1.0


    【解决方案1】:

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

    【讨论】:

    • GetSetting 似乎不再是 .Net Core 2.0 中 WebHostBuilder 的一部分。
    • @Alan 我还在 asp.net core 2.1 中使用它
    【解决方案2】:

    如果您想最终将 Https 证书的密码存储在 User Secrets 中,请在 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"]);
                })
    

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

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2012-07-16
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 2016-12-21
      相关资源
      最近更新 更多