如何从root获得强类型配置?

时间:2015-12-29 18:38:22

标签: configuration asp.net-core

在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之类的节点?

1 个答案:

答案 0 :(得分: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