IWebHostBuilder.GetSetting()没有appsettings.json数据

时间:2018-02-10 02:43:18

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

我正在努力将ASP.Net Core v1应用程序重构为v2。当前努力的要点是将数据库种子逻辑移动到Program.Main(),如MS docs所示......

  

在2.0项目中,将SeedData.Initialize调用移至Main   Program.cs的方法:

我遇到的问题是我需要从appsettings.json文件中获取配置标志。根据{{​​3}}调用WebHost.CreateDefaultBuilder时,默认情况下会加载显示,但我的代码无法从appsettings.json检索简单的标记

public static IWebHost BuildWebHost(string[] args)
{
    var builder = WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

    string env = builder.GetSetting("environment");
    var envMsg = "ASPNETCORE_ENVIRONMENT/Environment variable ";
    if (string.IsNullOrWhiteSpace(env))
        throw new ArgumentNullException("environment", envMsg + "missing!");
    else
        Console.WriteLine(envMsg + "found!");

    string doSeed = builder.GetSetting("SeedDb");
    var seedMsg = "SeedDb in appsettings.json ";
    if (string.IsNullOrWhiteSpace(doSeed))
        throw new ArgumentNullException("SeedDb", seedMsg + "missing!");
    else
        Console.WriteLine(seedMsg + "found!");

    return builder.Build();
}

environment变量已设置(为source),但json文件中的值似乎不是。 env检查没有例外,但种子标志上有。

回购expected以验证是否需要。我错过了什么?我已经看到提到使用“AppSettings”等搜索设置前缀...但是我没有在源代码中看到这一点(并且无法验证应该的内容,如果有的话。)

1 个答案:

答案 0 :(得分:0)

结合this SO的结果,我发现它......

public static void Main(string[] args)
{
    var host = BuildWebHost(args);

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var config = services.GetService<IConfiguration>(); // the key/fix!
        var s = config.GetValue<string>("SeedDb");
        var doSeed = bool.Parse(s); // works!
    }

    host.Run();
}

或只是var doSeed = config.GetValue<bool>("SeedDb");