IWebHostBuilder.GetSetting() doesnt have appsettings.json data

冷暖自知 提交于 2019-12-24 21:42:41

问题


I am working on refactoring an ASP.Net Core v1 application to v2. The gist of the current effort is moving the database seeding logic to Program.Main() as indicated in the MS docs...

In 2.0 projects, move the SeedData.Initialize call to the Main method of Program.cs:

The problem I am encountering is that I need to get a config flag out the appsettings.json file. This appears to be loaded by default when WebHost.CreateDefaultBuilder is called as per the source, but my code isn't able to retrieve a simple flag from my 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();
}

The environment variable is set (as expected), but the values from the json file do not appear to be. No exception on env check, but there is on the seed flag.

Repo here to verify if needed. What am I missing? I've seen mention of prefixing the setting to search for with "AppSettings", etc... but I don't see that indicated in the source (and can't verify what it should be, if anything.)


回答1:


Combining the results from this SO, I have it figured out...

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

Or just var doSeed = config.GetValue<bool>("SeedDb");!



来源:https://stackoverflow.com/questions/48716712/iwebhostbuilder-getsetting-doesnt-have-appsettings-json-data

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