本文介绍了IWebHostBuilder.GetSetting()没有appsettings.json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将ASP.Net Core v1应用程序重构为v2.当前工作的要旨是将数据库种子逻辑移至Program.Main(),如 MS文档 ...

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

我遇到的问题是我需要在appsettings.json文件中获取配置标志.当,但是我的代码无法从我的appsettings.json中检索一个简单的标志.

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

设置了environment变量(如期望),但json文件中的值似乎不正确. env检查没有异常,但是种子标志上有

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.

此处处回购,以验证是否需要.我想念什么?我已经看到提到要在搜索设置前添加"AppSettings"等前缀,但是我没有看到源中指示的内容(并且无法验证其应为,如果有的话.)

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

推荐答案

结合此SO 的结果,它想通了...

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

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

这篇关于IWebHostBuilder.GetSetting()没有appsettings.json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:39