asp.net core 2.1 ConfigurationBuilder的GetSection函数返回null

4

在 .net core 2.1 控制台应用程序中,ConfigurationBuilder Getsection() 返回 null。我已经搜索了很多博客和帖子,但是只有嵌套到3-4层的json示例。

目的是读取整个json中的“test”键以及它的元素并进行操作。我希望这个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

2
app2 is under test/Applications/app2. You will need to get the parent sections first. configuration.GetSection("test").GetSection("Applications").GetSection("app2") - ESG
继续说,你在末尾有一个额外的括号。JSON格式不正确。 - Tubs
要读取数组元素,需要执行以下操作: configuration.GetSection("test").GetSection("Applications").GetSection("app2").GetSection("Softwares") .GetChildren().ToArray().Select(c => c.Value).ToArray(); - Var
1个回答

3

也许可以尝试使用这个:

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

不适用于我的情况,无法读取,我的JSON中声明了数组。 - Var
要读取数组元素,必须执行以下操作: configuration.GetSection("test").GetSection("Applications").GetSection("app2").GetSection("Softwares") .GetChildren().ToArray().Select(c => c.Value).ToArray(); - Var

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接