【问题标题】:Configuration GetSection returns null value for object sections配置 GetSection 返回对象部分的空值
【发布时间】:2018-12-20 16:01:56
【问题描述】:

您好,我在 .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"
        }
    }
}

当我尝试GetSection("Config")GetSection("tt") 时,我得到了null 的值。但是它返回原始类型的值,例如我的情况Url

有趣的是,如果我在configuration.Providers[0].Data 里面偷看,我会看到图片中的所有内容:

为什么 object 类型返回 null?

代码

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

【问题讨论】:

标签: c# asp.net-core


【解决方案1】:

你的例子没有错。您所指的Value 属性是string,对于sectsect2 变量都是null,因为这两个变量都不包含string 值——它们都是对象,如你已经说过了。

如果您想从中提取一个值,例如sect2,您可以使用以下方法:

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

还有更多选项可用于获取此类部分的值。这是另一个绑定到 POCO 的示例:

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

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

如果您只想获取一个嵌套值,那么根本没有理由使用GetSection。例如,您可以执行以下操作:

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

【讨论】:

  • 我想拉出该部分但不将其绑定到POCO,因为接下来我只需要一个字段,在这种情况下我需要字段Dev
【解决方案2】:

两个答案(TanvirArjelKirk Larkin)都是正确的。 我只是想为您澄清一下,并提供另一种从配置文件中获取值的方法。

要从 appsettings.json 获取值,您需要将值的路径 (colon-separated) 传递给 configuration

在不将部分绑定到类的情况下,有多种方法可以获取值。例如:

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");

【讨论】:

  • 所以我尝试了configuration.GetSection("Config:Production).GetValue&lt;Address&gt;("RedisAddress"),但我仍然得到null。我也尝试过configuration.GetSection("Config:Production:RedisAddress).Value",我再次得到null。地址是struct。我无法提取对象?我需要一一提取原语吗?
  • 您可以创建一个类ProductionConfig,其中包含Address 结构,然后将生产配置检索为configuration.GetSection("Config:Production").Get&lt;ProductionConfig&gt;();。这应该有效。注意:Address 的名称应该与 Config:Production:Address 中的键匹配
  • 现在我有一个Address 的类。我是否也需要对封闭类型进行强类型,以便能够检索孩子?就我而言,我有RedisAddress 类型Address.我也需要强输入Dev/Production 部分吗?
  • 是的,否则你会得到类似failed to convert 'THE VALUE' to type 'Type' 的东西。您可以拥有要从配置中检索的属性,而不必拥有所有部分。
  • 我不确定,但可能是的,您需要尊重 Path 才能获得 json 的一小部分。或者您可以实现extension methods 来获取特定的部分/值,与Microsoft.Extensions.Configuration 提供的GetConnectionString 相同。
【解决方案3】:

var sect = configuration.GetSection("Config"); 返回 null,因为 Config 部分没有键和值,而是有一个 SubSection,即 ProductionKeyValue 位于此层次结构的最低级别。

Here 是微软在 ASP.NET Core 中读取appsettings.json 文件的详细信息。

根据上述文档,您需要执行以下操作才能从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

按照上述方法,您可以从appsettings.json 文件中读取任何值:

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多