【问题标题】:How can you get strongly-typed config from the root?如何从根目录获取强类型配置?
【发布时间】:2015-12-30 03:18:00
【问题描述】:

在 ASP .NET 5 中,您可以将 appsettings 映射到一个类。有关最新示例,请参阅 this answer

我看到的执行此操作的代码通常如下所示:

services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));

因此,您的appsettings.json 中应该有一个具有该名称的节点(示例取自本文):

{
    "AppSettings" : {
        "SiteTitle" :  "My Web Site"
    },
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
        }
    }
}

是否可以(从根)获取整个文件,而不必声明诸如AppSettings 之类的节点?

【问题讨论】:

    标签: configuration asp.net-core


    【解决方案1】:

    是的,你可以。使用ConfigurationBinder

     var configurationBuilder = new ConfigurationBuilder();
     // Add the providers that you want here
    
     var config = configurationBuilder.Build();
    
     var options = new StrongTypeObject();
     config.Bind(options);
    

    更多示例:https://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多