简体   繁体   English

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

[英]asp.net core 2.1 ConfigurationBuilder GetSection function return null

ConfigurationBuilder Getsection() return null on .net core 2.1 console application. ConfigurationBuilder Getsection()在.net core 2.1控制台应用程序上返回null。 I have been searched quite a few blogs and posts but there is json example where its nested upto 3-4 levels. 我已经搜索了不少博客和帖子,但有json示例,其嵌套高达3-4级。

Motive is to read the whole "test" key of json and its elements and do operations. 动机是阅读json及其元素的整个“测试”键并进行操作。 I want this json to be configurable outside the application, so it can be changed without making any changes in code. 我希望这个json可以在应用程序之外进行配置,因此可以在不对代码进行任何更改的情况下对其进行更改。 Below is the sample code 下面是示例代码

{
  "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

use this one maybe it work: 使用这个可能它的工作:

json: JSON:

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

startup: 启动:

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

and get data from: 并从以下数据获取数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM