Configuration.GetValue<T>返回 null 但 Bind 有效 [英] Configuration.GetValue&lt;T&gt; returning null but Bind works

查看:26
本文介绍了Configuration.GetValue<T>返回 null 但 Bind 有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从 appsettings.json 获取数据时遇到问题.该文件看起来像:

I'm having a problem getting data from my appsettings.json. The file looks like:

  "Integrations": {
    "System01": {
      "Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
      "User": "admin",
      "Password": "admin"
    },
    "System02": {
      "Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
      "User": "admin",
      "Password": "admin"
    },
  }

我有以下 DTO:

public class IntegrationsConfigurationDto
{
    public string Host { get; set; }
    public string User { get; set; }
    public string Password { get; set; }
}

当试图阅读它时:

var config = _configuration.GetValue<IntegrationsConfigurationDto>("Integrations:System01");

我得到 null.但如果我这样做:

I get null. But if I do:

var config = new IntegrationsConfigurationDto();
_config.Bind("Integrations:System01", config);

我在 config 变量中正确获取了值.

I get the values correctly in my config variable.

为什么会这样?在这种情况下如何使用 GetValue?

Why does that happen? How can I use GetValue<T> in this scenario?

提前致谢.

推荐答案

GetValue 仅适用于简单的值,例如 string, int等 - 它不会遍历嵌套配置的层次结构.

GetValue only works for simple values, such as string, int, etc - it doesn't traverse the hierarchy of nested configuration.

参考:中的配置ASP.NET 核心:获取价值

ConfigurationBinder.GetValue 从具有指定键的配置中提取值并将其转换为指定类型.如果未找到键,重载允许您提供默认值.

ConfigurationBinder.GetValue<T> extracts a value from configuration with a specified key and converts it to the specified type. An overload permits you to provide a default value if the key isn't found.

不要使用 Bind,而是使用以下内容来避免创建自己的 IntegrationsConfigurationDto 实例:

Instead of using Bind, use the following to avoid having to create your own instance of IntegrationsConfigurationDto:

var config = _configuration.GetSection("Integrations:System01")
    .Get<IntegrationsConfigurationDto>();

参考:ASP.NET Core 中的配置:绑定到对象图

ConfigurationBinder.Get 绑定并返回指定的类型.Get 比使用 Bind 更方便.

ConfigurationBinder.Get<T> binds and returns the specified type. Get<T> is more convenient than using Bind.

这篇关于Configuration.GetValue<T>返回 null 但 Bind 有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆