c# - asp.net core 2.1 ConfigurationBuilder GetSection 函数返回null

标签 c# .net-core console-application

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

Motive 是读取 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

最佳答案

使用这个也许它工作:

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

关于c# - asp.net core 2.1 ConfigurationBuilder GetSection 函数返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55798063/

相关文章:

C# 反射 : How to get the properties of the derived class from the base class

c# - 在 C# 中将 unicode 字符转换为单个十六进制值

.net-core - 被 CORS 策略阻止的 Blazor 请求

c# - .NET Standard 2.1 与 .NET Core 3.1 无法加载文件或程序集

c++ - 计算和数据限制

c# - 想要根据用户的输入更改 ForegroundColor

c# - 如何更改为另一个 View Controller (解释清楚)

entity-framework - EF Core 中的表值函数

c++ - 查找并替换字符数组中的单词

c# - 调用者未经服务验证