asp.net核心2.1 ConfigurationBuilder GetSection函数返回null

时间:2019-04-22 17:01:07

标签: c# .net-core console-application

ConfigurationBuilder Getsection()在.net core 2.1控制台应用程序上返回null。我被搜索了很多博客和帖子,但是有一个json示例,其中嵌套了3-4个级别。

动机是读取json及其元素的整个“测试”键并进行操作。我希望此json可在应用程序外部进行配置,因此无需更改代码即可对其进行更改。 下面是示例代码

{
  "test": {
    "test1": {
      "testing": {
        "ApplicationName": "Microsoft Visual Studio", 
        "appid": "123456", 
        "ApplicationProfile": {
          "Vs2015": "Microsoft Visual Studio 2015 Professional",
          "VS_2017_Restricted": "Microsoft Visual Studio 2017 Enterprise (Restricted)"
        }
      }
      },
      "Applications": {
        "app1": {
          "Name": "application1",
          "arrayOfSomething": [ "first array elment", "Secondarrayelement" ],
          "anotherarraylikeabove": [],

        },
        "app2": {
          "Name": "application2",
          "Softwares": [ "first array elment", "second element" ],
          "APACGroups": [],
          "EMEA": [],
          "OnlyForZurich": [] 
        }
      }
    }
  }
}
var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
var test  = configuration.GetSection("app2"); //test is null always

1 个答案:

答案 0 :(得分:0)

使用此方法可能会起作用:

json:

   "Locations": {
        "Location": [ "Ford", "BMW", "Fiat" ]
    },

启动:

 // Replace IConfiguration with IHostingEnvironment since we will build
    // Our own configuration
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddEnvironmentVariables()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        // Set the new Configuration
        Configuration = builder.Build();
    }

并从以下位置获取数据:

 public IActionResult Settings()
    {
       var array = Configuration.GetSection("Locations:Location")
           .GetChildren()
           .Select(configSection => configSection.Value);
       return View();
    }