首页 > 解决方案 > asp.net core 2.1 ConfigurationBuilder GetSection函数返回null

问题描述

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

标签: c#.net-coreconsole-application

解决方案


使用这个也许它工作:

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

推荐阅读