简体   繁体   English

配置 GetSection 返回对象部分的空值

[英]Configuration GetSection returns null value for object sections

Hello i am using aa json configuration file within a .NET Core App and i do not understand why i get the value null for subsections that are objects:您好,我在.NET Core App中使用json配置文件,但我不明白为什么我会为作为对象的子部分获取 null 值:

{
    "tt": {
        "aa":3,
        "x":4
    },
    "Url":333,
    "Config": {
        "Production": {
            "RedisAddress": {
                "Hostname": "redis0",
                "Port": 6379
            },
            "OwnAddress": {
                "Hostname": "0.0.0.0",
                "Port": 9300
            }
        },
        "Dev": {
            "RedisAddress": {
                "Hostname": "redis0",
                "Port": 6379
            },
            "OwnAddress": {
                "Hostname": "0.0.0.0",
                "Port": 9300
            },
            "Logger": "logger.txt"
        }
    }
}

When i try GetSection("Config") or GetSection("tt") i get the value null .It however returns the value for primitive types like in my case Url .当我尝试GetSection("Config")GetSection("tt")时,我得到的值为null 。但是它返回原始类型的值,例如我的Url

What is funny is that if i peek inside the configuration.Providers[0].Data i have all the content present like in the picture:有趣的是,如果我在configuration.Providers[0].Data内部窥视,我将拥有图片中的所有内容:

在此处输入图像描述

Why does it return null for object types?为什么它为object类型返回 null?

Code代码

WebHostBuilder builder = new WebHostBuilder();
builder.UseStartup<Startup>();

string appPath = AppDomain.CurrentDomain.BaseDirectory;
string jsonPath = Path.Combine(Directory.GetParent(Directory.GetParent(appPath).FullName).FullName, "appsettings.json");

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(appPath)
    .AddJsonFile(jsonPath, optional: true, reloadOnChange: true)
    .Build();

var sect = configuration.GetSection("Config");//has value null
var sect2 = configuration.GetSection("tt");//has value null
var sect3 = configuration.GetSection("Url"); has value 333

There is nothing wrong in your example.你的例子没有错。 The Value property you're referring to is a string , which is null for both your sect and sect2 variables simply because neither of these contain a string value - they are both objects, as you've stated.您所指的Value属性是一个string ,对于您的sectsect2变量都是null ,因为它们都不包含string值 - 正如您所说,它们都是对象。

If you want to pull out a value from eg sect2 , you can do so using something like this:如果你想从例如sect2中提取一个值,你可以使用这样的方法:

var aaValue = sect2.GetValue<int>("aa");

There are a few more options for getting the values for a section like this.还有更多选项可以获取这样的部分的值。 Here's another example that will bind to a POCO:这是另一个绑定到 POCO 的示例:

public class TT
{
    public int AA { get; set; }
    public int X { get; set; }
}

var ttSection = sect2.Get<TT>();

If all you want to do is get a nested value, there's really no reason to use GetSection at all.如果您只想获得一个嵌套值,那么根本没有理由使用GetSection For example, you can just do the following:例如,您可以执行以下操作:

var redisHostname = configuration["Config:Dev:RedisAddress:Hostname"];

Both answers ( TanvirArjel and Kirk Larkin ) are correct.两个答案( TanvirArjelKirk Larkin )都是正确的。 I am just going to clarify things for you and provide another way of getting the value form the configuration file.我只是要为您澄清一些事情,并提供另一种从配置文件中获取值的方法。

To get a value from appsettings.json you need to pass the path of the value ( colon-separated ) to the configuration .要从appsettings.json获取值,您需要将值的路径(以colon-separated )传递给configuration

There are different ways to get the value without binding the section to a class.有不同的方法可以在不将部分绑定到类的情况下获取值。 Eg:例如:

var aaAsString = configuration["tt:aa"]; //will return the value as a string "3".
//To get the actual value type you need to cast them 
var aa1 = configuration.GetValue<int>("tt:aa"); //returns 3.
var aa2 = configuration.GetSection("tt").GetValue<int>("aa");
var aa3 = configuration.GetSection("tt").GetValue(typeof(int), "aa");

var sect = configuration.GetSection("Config"); returns null because Config section has no key and value, instead it has a SubSection which is Production .返回 null 因为Config部分没有键和值,而是有一个SubSectionProduction Key and Value reside in the lowest level of this hierarchy. KeyValue位于此层次结构的最低级别。

Here is the details from Microsoft of reading appsettings.json file in ASP.NET Core. 是 Microsoft 在 ASP.NET Core 中读取appsettings.json文件的详细信息。

According to the above documentation you need to do as follows to read the values from appsettings.json file:根据上述文档,您需要执行以下操作才能从appsettings.json文件中读取值:

var hostName = configuration.GetSection("Config:Production:RedisAddress:Hostname").Value; // will return the value "redis0" for key `HostName`
var port = configuration.GetSection("Config:Production:RedisAddress:Port").Value; // will return the value 6379 for key `Port`
var aa = configuration.GetSection("tt:aa").Value; // will return 3

Following the above methodology you can read any value from the appsettings.json file:按照上述方法,您可以从appsettings.json文件中读取任何值:

This if how I made it work如果我是如何让它工作的

"Localization": {
  "DefaultCulture": "en-US",
  "SupportedCultures": [
    "en-US",
    "no-NB",
    "uk-UA",
    "ru-RU"
  ],
  "SupportedUICultures": [
    "en-US",
    "no-NB",
    "uk-UA",
    "ru-RU"
  ]
}
var localizationSection = this.configuration.GetRequiredSection("Localization");
options.AddSupportedCultures(localizationSection.GetRequiredSection("SupportedCultures").Get<string[]>());
options.AddSupportedUICultures(localizationSection.GetRequiredSection("SupportedUICultures").Get<string[]>());
options.SetDefaultCulture(localizationSection.GetRequiredSection("DefaultCulture").Get<string>());

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

相关问题 Configuration.GetSection返回null值 - Configuration.GetSection returns null value Configuration.GetSection 从 appsetting.json 获取值但 Configuration.GetSection.Bind 总是返回 null - Configuration.GetSection gets value from appsetting.json but Configuration.GetSection.Bind always returns null Configuration.GetSection 总是返回 Value 属性 null - Configuration.GetSection always returns Value property null 单元测试中的 HostBuilder:HostContext.Configuration.GetSection 返回值 null - HostBuilder in Unit Test: HostContext.Configuration.GetSection returns value null configuration.getValue 或 configuration.getsection 总是返回 null - configuration.getValue or configuration.getsection always returns null ASP.NET Core:JSON 配置 GetSection 返回 null - ASP.NET Core: JSON Configuration GetSection returns null ConfigurationManager.GetSection 返回 null - ConfigurationManager.GetSection returns null Configuration.GetSection(“的connectionStringName”)。获取 <?> 总是为空 - Configuration.GetSection(“ConnectionStringName”).Get<?> always null IConfiguration.GetSection()作为属性返回null - IConfiguration.GetSection() as Properties returns null ConfigurationSection ConfigurationManager.GetSection()始终返回null - ConfigurationSection ConfigurationManager.GetSection() always returns null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM