代码之家  ›  专栏  ›  技术社区  ›  Lost

getSection()很容易获取原始字符串值,但不是复杂值

  •  0
  • Lost  · 技术社区  · 7 年前

    这真让我吃惊。我正在使用 Configuration.GetSection 方法和简而言之my appsettings.json如下所示:

    "AppSettings": 
      {  
        "PathPrefix": "",
        "Something": "Something else",
        "Clients":{"foo": "bar"}
      }
    

    现在让我吃惊的是,如果我做了如下事情:

    var foo = Configuration.GetSection("AppSettings:Clients:foo").Value;
    

    然后它得到正确的值。它得到了价值 bar

    但是,当我这样做的时候

     var clients = Configuration.GetSection("AppSettings:Clients").Value;
    

    它返回空值。不只是这个领域,每次我打电话 getSection 方法获取任何复杂对象,然后返回null,但当我调用它获取基本字符串值时,它将正确获取该值。 尽管 看起来,它在获取父元素时遇到了问题。这让我困惑,并提出三个问题:

    1. 为什么在获取复杂值而不获取基本字符串值时会遇到问题?
    2. 是故意的吗?如果是,为什么?
    3. 如果我想加载整个对象,我该怎么做?
    2 回复  |  直到 7 年前
        1
  •  3
  •   Simply Ged Saeed    7 年前

    可以使用强类型对象加载整个对象。

    首先,创建一个(或多个)类来保存设置。根据您的示例,这看起来像:

    public class AppSettings
    {
        public string PathPrefix { get; set; }
        public string Something { get; set; }
        public Clients Clients { get; set; }
    }
    
    public class Clients
    {
        public string foo { get; set; }
    }
    

    现在,您需要将选项服务添加到服务集合,并从配置中加载设置:

    public void ConfigureServices(IServiceCollection services)
    {
        // This is only required for .NET Core 2.0
        services.AddOptions();
    
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    
        services.AddMvc();
    }
    

    现在可以通过将属性注入类来访问这些属性,例如:

    public class HomeController : Controller
    {
        private readonly AppSettings _settings;
    
        public HomeController(IOptions<AppSettings> settings)
        {
            _settings = settings.Value;
        }
    }
    

    也可以在 ConfigureService 方法指定要加载的配置节,例如

    services.Configure<Clients>(Configuration.GetSection("AppSettings:Clients");
    

    现在你可以注射了 IOptions<Clients> 访问这些设置

    官方文件可以找到 here

        2
  •  3
  •   Henk Mollema    7 年前

    你希望它会有什么回报?您可以使用 Get<T> 扩展方法。试试这个:

    var clients = Configuration.GetSection("AppSettings:Clients").Get<YourClientsType>();